开发者

Isnt setprecision not supposed to change the value stored in variable?

开发者 https://www.devze.com 2023-02-09 20:02 出处:网络
I was of the opinion that setprecision doesnt change the value in variable itself. Also, when you attach setprecision to cout, it sticks with i开发者_如何学Got only once. However, when I run code to v

I was of the opinion that setprecision doesnt change the value in variable itself. Also, when you attach setprecision to cout, it sticks with i开发者_如何学Got only once. However, when I run code to verify, it doesnt work.

Consider the following code snippet:

int main()
{
    double x = 9.87654321;
    cout << setprecision(3) << fixed << x <<endl;    //Returns 9.877 as it should
    cout << x << endl;                               //Returns truncated value 9.877 again though it shouldnt.

    return 0;
}   

Interesting part is, if we replace cout << x << endl; by a line setting precision to say 7, then it DOES display the correct value. Can anyone please explain this phenomenon?


You don't reset the precision to the original value so it's just using 3 as the precision value for both output operations.

If you want to restore the original precision then you need to save it. The initial value for standard ostreams is 6 which may not be accurate enough for many purposes.

int main()
{
    double x = 9.87654321;

    size_t save_prec = cout.precision();
    cout << setprecision(3) << fixed << x <<endl;
    cout.precision(save_prec);

    cout << x << endl;

    return 0;
}


It sets the precision of the output stream, not x, meaning after the call to setprecision(3), cout outputs all numbers with precision of 3.

http://www.cplusplus.com/reference/iostream/manipulators/setprecision/

Try this, which will show that x has not changed.

int main() 
{     
  double x = 9.87654321;     
  cout << setprecision(3) << fixed << x <<endl;    //Returns 9.877 as it should     
  cerr << x << endl;                               //Returns 9.87654 to stderr  
  return 0; 
} 


Other answers have indicated the problem. One possible solution is to use the Boost I/O Stream state saver library to do the work of saving the I/O stream formatting state and restoring it at the appropriate time.

0

精彩评论

暂无评论...
验证码 换一张
取 消