Dart中的整数除法-'double'类型不是'int'类型的子类型 [英] Integer division in Dart - type 'double' is not a subtype of type 'int'

查看:1109
本文介绍了Dart中的整数除法-'double'类型不是'int'类型的子类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Dart中遇到整数除法时遇到了麻烦,因为它给了我错误:违反异常:类型'double'不是'c'的'int'类型的子类型。

I have trouble with integer division in Dart as it gives me error: 'Breaking on exception: type 'double' is not a subtype of type 'int' of 'c'.'

下面是以下代码:

int a = 500;
int b = 250;
int c;

c = a / b; // <-- Gives warning in Dart Editor, and throws an error in runtime.

如您所见,我期望结果应为2,或者说,即使除以'a'或'b'的结果将是浮点/双精度值,应将其直接转换为整数值,而不要这样抛出错误。

As you see, I was expecting that the result should be 2, or say, even if division of 'a' or 'b' would have a result of a float/double value, it should be converted directly to integer value, instead of throwing error like that.

I通过使用.round()/。ceil()/。floor()可以解决此问题,但这并不能满足我的程序要求,这一小小的操作至关重要,因为在一次游戏更新中它被调用了数千次(或者可以在requestAnimationFrame中说)。

I have a workaround by using .round()/.ceil()/.floor(), but this won't suffice as in my program, this little operation is critical as it is called thousands of times in one game update (or you can say in requestAnimationFrame).

我还没有找到其他解决方案,知道吗?谢谢。

I have not found any other solution to this yet, any idea? Thanks.

Dart版本:1.0.0_r30798

Dart version: 1.0.0_r30798

推荐答案

因为 Dart使用 double 表示 dart2js 中的所有数字。如果您使用以下方法,则可以获得有趣的结果:

That is because Dart uses double to represent all numbers in dart2js. You can get interesting results, if you play with that:

代码:

int a = 1; 
a is int; 
a is double;

结果:

true
true

实际上,建议使用类型 num 涉及数字,除非您有充分的理由将其设置为 int (例如,在for循环中)。如果要继续使用 int ,请使用截断符,如下所示:

Actually, it is recommended to use type num when it comes to numbers, unless you have strong reasons to make it int (in for loop, for example). If you want to keep using int, use truncating division like this:

int a = 500;
int b = 250;
int c;

c = a ~/ b;

否则,我建议使用 num 类型。

Otherwise, I would recommend to utilize num type.

这篇关于Dart中的整数除法-'double'类型不是'int'类型的子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆