我認爲setprecision並沒有改變變量本身的值。另外,當你將setprecision附加到cout時,它只會使用一次。但是,當我運行代碼進行驗證時,它不起作用。Isnt setprecision不應該改變存儲在變量中的值嗎?
考慮下面的代碼片段:
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,那麼它會顯示正確的值。任何人都可以解釋這種現象嗎?
可能相關:http://stackoverflow.com/questions/1532640/which-iomanip-manipulators-are-sticky/1533752#1533752 – 2011-02-11 17:59:28