# Thread: Float discrepencies

1. ## Float discrepencies

I have a question about adding floats. Seems that when I do the following code:

Code:
```#include <climits>
#include <iostream>
using namespace std;

int main()
{
float x;
int i;
x = 1.0;
i = 0;
while (i < 1000)
{
cout << "x = " << x << endl;
x = x + .0001;
i++;
}
return 0;
}```
the end result is not right. At 1.0301 it's fine, but then it adds an extra one at the end for the next float, i.e. 1.03021. It then does it again at 1.09031, where the next one is 1.09042 (where the last digit 1 and 2 respectively are not even supposed to be there).

I'm thinking that this is because the numbers are of type float and I've read that "float is often merely an approximation of the desired value"

Am I right or is there another reason? This may seem like a silly question, but I would like to understand why it behaves like it does.

As always, any comments is appreciated.

2. ## Is this what your after...

Greetings,
using the iomanip class enables you to format your code.
Code:
```#include <climits>
#include <iostream>
#include<iomanip>	//used for format manipulation
using namespace std;

int main()
{
float x;
int i;
x = 1.0;	//this is not an integer
i = 0;
for (i = 0; i < 1000; i++)
{
cout << "x = " << setprecision(4) <<fixed<< x << endl;	//sets decimal right
//only 4 spaces
x = x + .0001;
}
return 0;
}```
ps. your right numbers l(eg; PI is approx.)

I hope this helped.
cj

3. Thanks guys!! It answered my question!!!

Popular pages Recent additions