Why does this math operation overflow?

  • Thread starter Thread starter Unknown
  • Start date Start date
U

Unknown

Why does this overflow?

long testmath = (898 * 360 + 30) * 24 * 60 * 60 * 1000 / 25;

but if I do it this way it works..

long testmath1 = (898 * 360 + 30)
long testmath2 = testmath1 * 24 * 60 * 60 * 1000 / 25;

How can I get it so that it works properly in the first definition..?

Thanks.
 
I believe the reason it works is that all of the operands are evaluated
as signed 32-bit integers, causing the overflow. When you assign the value
to testmath1, it is a long, which causes the second expression to have all
of its operands converted to 64 bit integers. In order to get this to work
in one line, this should work:

long testmath = ((long) (898 * 360 + 30)) * 24 * 60 * 60 * 1000 / 25;

Hope this helps.
 
Unknown said:
Why does this overflow?

long testmath = (898 * 360 + 30) * 24 * 60 * 60 * 1000 / 25;

but if I do it this way it works..

long testmath1 = (898 * 360 + 30)
long testmath2 = testmath1 * 24 * 60 * 60 * 1000 / 25;

How can I get it so that it works properly in the first definition..?

Thanks.

The first expression overflows because all of the components of the
expression are of type Int32 (the assignment destination is not used to
determine the expression type).

In your second instance, testmath1 has type Int64, so the expression is
also Int64.

You can get the first expression to work by casting one or more of the
operands to Int64 or long:

long testmath = ((long) (898 * 360 + 30)) * 24 * 60 * 60 * 1000 / 25;
 
Hi Unknown,
Just let at least one of the constant have to *L* sufix.
long testmath = (898L * 360 + 30) * 24 * 60 * 60 * 1000 / 25;
This will do the trick.

HTH
B\rgds
100
 
Back
Top