2012-09-12 27 views
1

我試圖運行下面的程序,它的工作原理,但是當我輸入的值超過6位小數時,它會一直變圓/截斷,例如2.999999 - > 3.我如何設置它,使其停止這樣做?爲什麼我輸入的數字只能讀到6位有效數字?

int main() 
{ 

    double n=0, x=0; 

    while (cin >> n >> x) //will keep going until an integer is not entered 
    { 
     cout << "You entered the two integers " << x << " and " << n << endl; 

     if (x-n <= (1.0/10000000) && n-x <= (1.0/10000000)) 
      cout << "The numbers are almost equal" << endl; 
    } 

return 0; 

} 
+2

你確定它的四捨五入/截斷輸入,或者是它發生在輸出呢? IIRC,'cout'的標準格式化雙打默認設置爲6個重要位置,除非您設置適當的標誌來告訴它否則... – twalberg

+0

yeh它正在輸出... – Physbox

+0

兩個建議。首先,註釋和文本引用「整數」,但值有double類型;這應該可能是固定的。其次,如果使用'abs(x - n)',測試可以變得更簡單;'這樣只需要一個測試。 –

回答

1

你可以改變你使用std::setprecision打印值的精度:

cout << "You entered the two integers " << setprecision(20) << x 
    << " and " << n << endl; 

Link to ideone.

+0

是否沒有辦法設置精度之前的cout聲明,即在我宣佈開始的地方n和x? – Physbox

+1

@ user1542646絕對 - 您可以自由地將'cout << setprecision(20);'移動到程序的任何部分。精度將保持有效,直到您爲其設置不同的值。 – dasblinkenlight

+0

哦,偉大的thx爲您的幫助。 – Physbox

相關問題