2016-01-16 70 views
2

我想創建一個C++程序來計算3張的正數格式化數字到n位小數沒有四捨五入

的平均

其中(x,Y,Z)> 0和(X,Y,Z)< = 10

我有這樣的代碼:

#include <iostream> 
#include <cstdio> 
#include <math.h> 

using namespace std; 

int main() 
{ 
    int x,y,z; 
    cin >> x >> y >> z; 
    double x1,y1,z1,ma; 
    x1 = x; 
    y1 = y; 
    z1 = z; 

    if(x>0 && x<=10 && y>0 && y<=10 && z>0 && z<=10) 
     ma = (x1+y1+z1)/3; 
    else 
     return 0; 

    printf("%.2f" , ma); 

    return 0; 
} 

對於x = 9,Y = 9,並且z = 5的平均值爲23/3 = 7.666666666666667並且當我格式化爲2位小數,其結果將是7.67,但我想出現7.66而不是7.67。

請問,有人可以幫助我嗎?

謝謝!

回答

4

不使用其他功能,你可以這樣做:

double x = (double)((int)(23 * 100/3))/100.0; 

甚至有點簡單:

double x = (double)(int)(23 * 100/3)/100.0; 

int投截斷剩下的數字(所以沒有四捨五入)。

在C++ 11中,還有trunc()函數可以做到這一點。