我认为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,那么它会显示正确的值.谁能解释一下这个现象吗?
c++ ×1