Java – unexpected result when dividing int by int and storing the result as double

See English answers > java program using int and double 7

This code just divides one int by another, stores the result in a double variable and prints it:

int a = 200;
int b = 557;

double divisionResult = a / b;

System.out.println("Result: " + divisionResult);@H_301_15@ 
 

执行此代码后,输出为:

Result: 0@H_301_15@ 
 

这很奇怪,因为200/557是0.3590664272890485

我注意到如果我在分界线上施放a和b加倍

double divisionResult = (double) a / (double) b;@H_301_15@ 
 

它完美地运作.

为什么我必须将变量转换为double来获得真正的除法结果?

Solution

Because in integer division, if the answer is not a complete integer, the number after the decimal point will be deleted (integer division produces integer value)

Note that you do not have to cast two integers, you can only convert one, and the second will be implicitly converted

Why after the actors?

Because the cast takes precedence over / So first it projects, then it separates If not, you will get 0.0

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>