Question

I have never used floats really that much before and the current project I am working on requires them. I'm getting weird issues that I learned about years ago but have forgotten why this happens.

My results after multiplying or adding floats aren't what they're supposed to be.

Here is my code:

void main ()
{
    //Example 1 - ERROR
    float a=16937.6;
    float b=112918;
    float total=b+a;
    cout<<total<<endl; //Outputs 129896 - rounds up and loses decimal (129855.6)

    //Example 2 - Error
    float c=247.82;
    float d=9995.2;
    float total2=c+d;
    cout<<total2<<endl; //Outputs 10243 - loses all decimals (10243.02)
    system ("pause");

}
Was it helpful?

Solution

Your problem isn't decimal precision - it's the format that is used to output the values.

Try:

cout << setiosflags(ios::fixed) << setprecision(2) << x;

OTHER TIPS

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top