Earlier I came up with something, which I solved, but it got me later let's take a look at a similar example of what I was on:
int b = 35000000; //35million
int a = 30000000;
unsigned long n = ( 100 * a ) / b;
Output: 4294967260
I simply changed a
to unsigned long
and the correct 85% output would come up, because a
is a signed 32bit integer. But this got me later. There is no value assignment to a
during ( 100 * a )
there is just simply a calculation and the correct value which is 3billion should come up instead of an overflow. To understand if there wasn't really an assignment to a
I removed a
from the code and manually write the value instead instead:
int b = 35000000;
unsigned long n = ( 100 * 30000000 ) / b;
The big surprise was that the output is also: 4294967260
And of course value of 3billion can be assigned to an unsigned long
.
My first thought was that ( 100 * 30000000 )
was causing an overflow, but then I asked "an overflow on what? there is nothing to be overflowed".
Then I changed b
to unsigned long, which even most suprisingly the output was correct 85%.
In the first example changing a
to unsigned long
int b = 35000000;
unsigned long a = 30000000;
unsigned long n = ( 100 * a ) / b;
and leaving b
as an int
as it is works, but on the second example it doesn't, what is occuring?
This might be a little overwhelming to let me re-write all examples with the ones who work and the ones who dont.
Works (Output = 85):
int b = 35000000;
unsigned long a = 30000000;
unsigned long n = ( 100 * a ) / b;
Works (Output = 85):
unsigned long b= 35000000;
unsigned long n = ( 100 * 30000000 ) / b;
Doesn't works (Overflow):
int b = 35000000;
int a = 30000000;
unsigned long n = ( 100 * a ) / b;
Doesn't works (Overflow):
int b = 35000000;
unsigned long n = ( 100 * 30000000 ) / b;