我认为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;
}
Run Code Online (Sandbox Code Playgroud)
有趣的是,如果我们用cout << x << endl;线设置精度替换为7,那么它会显示正确的值.谁能解释一下这个现象吗?
您不会将精度重置为原始值,因此它只使用3作为两个输出操作的精度值.
如果要恢复原始精度,则需要保存它.标准ostreams 的初始值为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;
}
Run Code Online (Sandbox Code Playgroud)