[英]Why does my variable resut in an overflow in Java?
Here is my code num1
etc are int
variable这是我的代码num1
等是int
变量
double numProduct1;
numProduct1 = (num1 * num2 * num3 * num4);
System.out.printf("%.3f ", numProduct1);
Inputs are respectively (num1,num2,num3,num4): 100000 200000 300000 500000
输入分别为 (num1,num2,num3,num4): 100000 200000 300000 500000
my code would output -1679818752.000
instead of 3000000000000000000000.000
我的代码会输出-1679818752.000
而不是3000000000000000000000.000
You thought that assigning the product to a double
will allow you to use the whole range of double
, but that isn't the case.您认为将产品分配给double
将允许您使用double
的整个范围,但事实并非如此。 You are only converting the result to double
.您只是将结果转换为double
。 The multiplication is still carried out with int
, and the int
range applies.乘法仍然使用int
,并且int
范围适用。
Essentially, this is the multiplication version of this common question (well, not exactly :D).本质上,这是这个常见问题的乘法版本(嗯,不完全是:D)。
The fix is similar, simply make the first operand double
(eg by casting):修复方法类似,只需将第一个操作数double
(例如通过强制转换):
numProduct1 = ((double)num1 * num2 * num3 * num4);
The expression is now a double
multiplied by an int
, and numeric promotion occurs, promoting the other numbers to double
as well.该表达式现在是一个double
乘以一个int
,并且发生了数字提升,从而将其他数字也提升为double
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.