2011-02-11 72 views
2

我認爲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,那麼它會顯示正確的值。任何人都可以解釋這種現象嗎?

+0

可能相關:http://stackoverflow.com/questions/1532640/which-iomanip-manipulators-are-sticky/1533752#1533752 – 2011-02-11 17:59:28

回答

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

所以在這種情況下,如果我做了像y = x之類的東西,將精度設置爲3,然後打印y,它應該打印完整的值?但後來我嘗試了它,它不! – Scranton 2011-02-11 17:49:44

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

其他回答指出問題所在。一種可能的解決方案是使用Boost I/O Stream state saver庫來完成保存I/O流格式化狀態並在適當的時候恢復它的工作。