• Status: Solved
• Priority: Medium
• Security: Public
• Views: 545

Long or double in c++

I have a calculation which gives me a result of:4391552000.

I have an int trying to store this and when I output it to the debugger I get:25866.

The result is this in the output debug window:
``````25866 = 1000 * (548944 * 8) / 3734
``````

I have read tha the max number an int can hold is: 4294967 296.

So,
Question 1.
What exactly is happening to turn my number from 4391552000 to 25866.

Question 2.
What should I use, a long or a double??
0
Wanting2LearnMan
5 Solutions

Commented:
Question 2:
You should use a Double. It can store numbers up to 15 digits. Int only gives the maximum number of 2147483647.
0

Commented:
1000*(548944*8)%(2^32)=96584704
96584704/3734  = 5866

Do longs in your c++ implementation hold at least 33 bits?

0

Commented:
Assuming a 32bit unsigned int, (1000 * (548944 * 8)) overflows to 96584704, which becomes 25866 when divided by 3734.

It's probably best to look at the hexadecimal representations of the values :

548944                                                            0x00086050
548944 * 8 = 4391552                                    0x00430280
548944 * 8 * 1000 = 4391552000                  0x105C1C400

That last value is too big for a 32 bit integer, so it's truncated to 0x05C1C400 :

truncated -> 96584704                                    0x05C1C400
96584704 / 3734 = 25866                              0x0000650A

>> What should I use, a long or a double??

That depends entirely on your purpose.

If you want an integer value, check if your platform supports a 64bit unsigned integer type (uint64_t eg.).
If you want a floating point value, then double should do fine.
0

Commented:
I like Infinity08's answer but would like to add my own questions.

Could you share your purpose?  I'll tell you to use 64 bit integers if you are writing guidance software for something like a Patriot Missile.  You'll get more questions if you say this is for a class.

Please do not give me any points for this post.
0

Commented:
the microsoft compiler has a MulDiv function for this common problem. it takes three int arguments number, numerator and denominator and returns an int.  number and numerator were multiplied using a 64-bit integer temporary and the result of the multiplication was divided by the denominator.

if you want to keep the code portable, you easily can make such a helper yourself.

Sara
0

Featured Post

Tackle projects and never again get stuck behind a technical roadblock.