Hi Guys, can you please look at this code. I'm wondering if it's something to do with how many bits my CPU has (I don't really know):
The code: #include <iostream>
using namespace std;
int main()
{
int intVar = 1500000000; //1,500,000,000
intVar = (intVar * 10) ; //result too large
cout << "intVar = " << intVar << endl; //wrong answer
Please be careful when copying values. The correct value is 2115098112.
Anyway,
intVar = 1,500,000,000
Why do you suppose you'd get this value, after multiplying the value by 10?
As for -2147483648, that seems to be the result of converting from double to int when the real value doesn't fit.
Thanks for youe reply Helios.
I thought a double type will be big enough for a number as big as 15 digits. but why doesn't it fit in. Is it because of my CPU (or machine) or something else?
Also I tried long double and it was the same result.
Helios sorry, I had problem while copying i should get intVar = 15,000,000,000 instead but I don't think it fit in double type.
Why is that? thank you!
No, you misunderstood me. 15 billion fits easily in a double, but when you convert from double to int, there's an implicit function call that takes the double and tries its best to assign it to the int. If, like in this case, the value can't possibly fit in the int, the function instead assigns INT_MIN (in your implementation, -2^31) to the int.
1 bit: 2
2 bit: 3
4 bit (nibble): 15
1 byte (8 bits): 255
2 bytes (word, size of common int and short): 65535
4 bytes (32 bit, size of large int, float, and long): 2147483647
8 bytes (64 bit, double wide integer or longlong, requires 64 bit processor if allocated at once): 9223372036854775807
These don't included the unsigned values. To get the unsigned value, just multiply signed value by two. The absolute value of the answer to signed value times 2 is the highest value. An unsigned value may not be below zero but the positive size is double.
Thank you Computerquip, i think you understood my issue. i think my machine has possibly a 32bit processor (don't really know) that's may be why 15 billion doesn't fit in a variable of type double.
Does it make sens at all?
A long long works on 32 bit processors, just is split into two different variables or 32 bit values when compiled. The compiler handles this for you. Of course, it's still good to make a macro to check for a 64 bit proc for each long long you create.
Don't quote me on this, I remember researching this when I first started C++ over a year ago.