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
In C++, there are programming elements called "literal constants".
For example (taken from here):
157 // integer constant
0xFE // integer constant
'c' // character constant
0.2 // floating constant
0.2E-01 // floating constant
"dog" // string literal
So, back to your example, 100 * 30000000
is multiplying two int
s together. That is why there is overflow. Anytime you perform arithmetic operations on operands of the same type, you get a result of the same type. Also, in the snippet unsigned long a = 30000000;
, you are taking an integer constant 30000000
and assigning that to the variable a
of type unsigned long
.
To get your desired output, add the ul
suffix to the end: unsigned long n = ( 100ul * 30000000ul ) / b;
.
Here is a site that has explanations for the suffixes.
why /b when b is unsigned long is still an interesting question
Because 100 * 30000000
is performed before you divide by b
and the operands are both of type int
.