0

i ran my program and i saw in program log that one of my arguments is wrong so i tried to debug it ,

i was trying to execute this:

double test = ((9 + 13) * (9 + 1594) * (2157 + 13) * (2157 + 1594));

the answer must be 287053602220 but it gives me -7.09206612E8

when i try

    double t1 = (9 + 13) * (9 + 1594);
    double t2 = (2157 + 13) * (2157 + 1594);
    test = t1 * t2;

it gives me a true result

what is the reason ?

Sergiu Paraschiv
  • 9,929
  • 5
  • 36
  • 47
  • Terrible question title! Please be more specific in your question titles to help people find questions. – Robin Green Nov 30 '13 at 12:55
  • That answer is, of course, perfectly correct, it just didn't match your expectations. All the parts of that expression are `int`s, so the `int` semantics are used. 287053602220 can not be represented as `int`, it wraps to -709206612 (which is then converted to a `double`, when it's already too late). – harold Nov 30 '13 at 13:00

3 Answers3

5

The first equation is computed as an Integer and then converted to a double. And you extend over INTEGER_MAX and get into the negative value. The first is equal to this:

//temp extends INTEGER_MAX so it gets negative.
int temp = (9 + 13) * (9 + 1594) * (2157 + 13) * (2157 + 1594));
double test = = (double) temp;

In the second you convert to a double earlier so you extend the value range and don't get into the negative range by extending over INTEGER_MAX.

Integers value range is from -2,147,483,648 to 2,147,483,647. If your numbers goes out of range is starts on the other side again. This way your number gets negative. Double has a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d. By converting within your equation you extend the range of values and your number does not go out of range and starts over in the negative range.

Simulant
  • 19,190
  • 8
  • 63
  • 98
1

You can see the type conversion,the (9 + 13)、(9 + 1594)、(2157 + 13)、(2157 + 1594) is all int,so it execute with int,after get the result then convert to the flot.You can try double test = ((float)(9 + 13) * (float)(9 + 1594) * (float)(2157 + 13) * (float)(2157 + 1594));

0

int Multiplied int ,the answer is also int ,so it din't give you the right answer,you can try ((9L + 13) * (9 + 1594) * (2157 + 13) * (2157 + 1594)) ,then the answer is right