为什么我的int 0?

Get*_*awn 1 java math

可能重复:
为什么int exp1 = 14/20*100; 在java中等于'0'?

我用这个:

int newWidth = Math.round(297 * (40 / 414));

在代码中,数字实际上是变量,但这些是他们持有的,当我运行时代码newWidth返回为0,我期待28或29.我没有看到这里有什么问题...

Tom*_*icz 9

40 / 414被舍入到0立即,因为它只适用于整数.您必须将其中一个操作数强制转换为double/ floatdouble立即使用:

int newWidth = (int)Math.round(297 * (40.0 / 414));
Run Code Online (Sandbox Code Playgroud)

要么:

int newWidth = (int)Math.round(297 * ((double)40 / 414));
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 5

因为40/414等于0,所以297*0 = 0Math.round(0) = 0

改为使用双打.