2013-11-03 76 views
2

我有這樣的代碼(很基本的):如何顯示在C++中位數的固定數量沒有四捨五入

#include <iostream> 
#include <iomanip> 

using namespace std; 
int main() 
{ 
float a = 0.0, 
     b = 0.0, 
     c = 0.0; 

cout<<"Input a: "; 
cin>>a; 
cout<<"input b: "; 
cin>>b; 
cout<<endl; 
c = a/b; 

cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl; 
return 0; 
} 

當我輸入兩個數字(比如,A = 513和B = 791)我得到0.65 。計算器顯示正確的答案是0.648。我知道我的代碼將最後一位小數加起來,但這不是我想要的。

我怎樣才能把它保持在0.64而不是0.65?

+0

您應該檢查是否'CIN >>了'返回TRUE。否則,輸入失敗。 –

回答

4

如果您想將值截斷到小數點後兩位,你可以乘以100吧,截斷爲整數,然後除以100,這樣的:

c = a/b; 
c = floor(100 * c)/100; 
cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl; 

Demo on ideone.

+0

哪個庫有trunc導致我有vs 2012的cmath,它沒有采取 – user2529011

+0

@ user2529011它是''(參見演示,我爲它添加了一個'#inc')。 – dasblinkenlight

+0

我做了,它仍然沒有把它 – user2529011

2

你可以使用trunc截斷到一定數目的數字:

c = a/b; 

// truncate past two decimals: 
c = trunc(c * 100)/100; 

cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl; 
的一個通用功能

int trunc(double val, int digits) 
{ 
    double pow10 = pow(10,digits); 
    return trunc(val * pow10)/pow10; 
} 

然後用

cout << "Result: " << fixed << setprecision(2) << trunc(c,2) << endl; 
+0

哪個庫具有trunc導致我在vs 2012中創建了cmath,並且沒有采用它 – user2529011

+0

或者,您可以在不使用trunc方法的情況下將'double'轉換爲'int'。 – RusI