Home > Software design >  Why does C increment a double with more than 6 decimals into next decimal number, without actually
Why does C increment a double with more than 6 decimals into next decimal number, without actually

Time:01-13

Why does this behaviour happen? that decimal after 6th place are incremented to next one in double but not increment when converted to int.

It is causing issues when converting to int, because despite printing 3, d1 still converts to 2 when converting to integer and not 3

    double d1 = 2.999999; //6 digits after decimal
    double d2 = 2.777777;
    
    double d3 = 2.77777;  //5 digits after decimal
    double d4 = 2.99999;  
    
    cout<<d1<<endl;       //gives 3
    cout<<(int)d1<<endl;  //still gives 2 not 3
    cout<<d2<<endl;       //gives 2.777778
    
    cout<<d3<<endl;       //gives 2.77777 as expected
    cout<<d4<<endl;       //gives 2.99999 as expected

I am assuming that it has to do something with compilers or precision but i am not sure of this unexpected behaviour. Kindly help

CodePudding user response:

It's because the default precision of cout is 6. The compiler recognizes the all values exactly enough, but the output is rounded to 6 decimal places. If you want the exact result, you can change the code like this:

cout << setprecision(7);
double d1 = 2.999999; //6 digits after decimal
double d2 = 2.777777;

double d3 = 2.77777;  //5 digits after decimal
double d4 = 2.99999;  

cout<<d1<<endl;       //gives 2.999999
cout<<(int)d1<<endl;  //still gives 2 not 3
cout<<d2<<endl;       //gives 2.777777

cout<<d3<<endl;       //gives 2.77777 as expected
cout<<d4<<endl;       //gives 2.99999 as expected
  • Related