Truncation and floating?

Jun 21, 2014 at 11:02pm
Hi! I need urgent help with a code where I frind the product of 10, 100, 1000, and 10000. So the actual answer would be 10,000,000,000 but when i write out my code the product that it gives me is 1.41007E9 which isn't true. I know that I'm supposed to truncate it somehow but im completely lost and i feel like I've tried everything. Can someone please help me!! Thanks :)
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main()
{
   float x = (10 * 100 * 1000 * 10000);
   cout << "the product of 10, 100, 1000, and 10000 is = " << x << " " << endl;
   return 0;
}
Last edited on Jun 21, 2014 at 11:03pm
Jun 21, 2014 at 11:06pm
You are doing integer multiplication and an integer is not large enough to hold the value generated, so you get overflow.

float x = 10.0 * 100 * 1000 * 10000 ;
Jun 21, 2014 at 11:08pm
how do i fix this then? would i use double instead of float?
Jun 21, 2014 at 11:09pm
oh wait I just fixed it!! Oh my god you have no idea how amazing you are!! thank you so much!!!! I really appreciate it!!!
Jun 21, 2014 at 11:09pm
float x = 10.0 * 100 * 1000 * 10000 ;
Jun 21, 2014 at 11:32pm
closed account (EwCjE3v7)
But I do not understand why he used a float.

He could have used int, which is faster. And if he wanted to get a floating point num then he couldve used double as double is faster on some systems
Jun 21, 2014 at 11:58pm
He could have used int, which is faster.
For a single calculation like this speed is not a concern.
10 * 100 * 1000 * 10000 gives 10000000000 which requires 34 bits to represent as a binary integer. Many implementations use 32-bit integers - indeed that was the cause of the original error and why this question was posted in the first place.
Topic archived. No new replies allowed.