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
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
(eg 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.