Isnt setprecision不应该改变存储在变量中的值吗?

时间:2011-02-11 17:41:48

标签: c++

我认为setprecision不会改变变量本身的值。此外,当您将setprecision附加到cout时,它只会粘贴一次。但是,当我运行代码进行验证时,它不起作用。

请考虑以下代码段:

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;
}   

有趣的是,如果我们用行设置精度将cout << x << endl;替换为7,那么它会显示正确的值。有人可以解释一下这种现象吗?

3 个答案:

答案 0 :(得分:5)

您不会将精度重置为原始值,因此它只使用3作为两个输出操作的精度值。

如果要恢复原始精度,则需要保存。标准ostream s的初始值为6,对于许多目的而言可能不够准确。

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;
}

答案 1 :(得分:0)

它设置输出流的精度,而不是x,这意味着在调用setprecision(3)之后,cout输出精度为3的所有数字。

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

试试这个,这表明x没有改变。

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; 
} 

答案 2 :(得分:0)

其他答案表明了问题。一种可能的解决方案是使用Boost I/O Stream state saver库来保存I / O流格式化状态并在适当的时间恢复它。