1

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 Answers1

3

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313