英文:
Why does my variable resut in an overflow in Java?
问题
这是我的代码
num1
等是 int
变量
double numProduct1;
numProduct1 = (num1 * num2 * num3 * num4);
System.out.printf("%.3f ", numProduct1);
输入分别为 (num1,num2,num3,num4):
100000
200000
300000
500000
我的代码输出会是 -1679818752.000
而不是 3000000000000000000000.000
。
英文:
Here is my code
num1
etc are int
variable
double numProduct1;
numProduct1 = (num1 * num2 * num3 * num4);
System.out.printf("%.3f ", numProduct1);
Inputs are respectively (num1,num2,num3,num4):
100000
200000
300000
500000
my code would output -1679818752.000
instead of 3000000000000000000000.000
答案1
得分: 3
你以为将产品分配给 double
将允许您使用整个 double
范围,但事实并非如此。您只是将 结果 转换为 double
。乘法仍然使用 int
进行,且适用于 int
范围。
本质上,这是乘法版本的 这个常见问题(嗯,不完全一样 :D)。
修复方法类似,只需使第一个操作数为 double
(例如通过强制转换):
numProduct1 = ((double)num1 * num2 * num3 * num4);
现在,表达式是一个 double
乘以一个 int
,并且会发生 数值提升,将其他数字也提升为 double
。
英文:
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. You are only converting the result to double
. The multiplication is still carried out with int
, and the int
range applies.
Essentially, this is the multiplication version of this common question (well, not exactly :D).
The fix is similar, simply make the first operand double
(e.g. by casting):
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论