2015-04-04 203 views
0

我有一些float變量會產生像1.23456789這樣的值。我想把它四捨五入到小數點後四位。如何在C++中將變量四捨五入到小數點後n位

setprecision函數只是舍入輸出,但我想更改變量本身的值。

所以我在尋找類似

x=roundoff(x,n) 

,其中舍入將四捨五入X到n位小數。

+2

對於某些值,這是不可能的。 – usr2564301 2015-04-04 14:36:20

+0

@Jongware可以請你詳細說明一下嗎? – 2015-04-04 14:37:57

+0

近似值可以是round(x * tenToTheNth)/ tenToTheNth,但請記住,由於浮點數的性質,這通常不會給出精確的值。 – 2015-04-04 14:39:19

回答

1

爲什麼不呢?

float val = 1.23456789 

    float rounded_down = floorf(val * 1000)/1000; /* 1.2345 */ 

編輯:

在評論中指出記住,這是一個近似,但它可能在很多情況下是可以接受的。 還喲可能要舍入到最接近值或圍捕如下:

float val = 1.23456789 

    float near = roundf(val * 1000)/1000; /* nearest */ 
    float up = ceilf(val*1000)/1000; /* up*/ 
3

這雙,少用浮準確那種-的確定。就個人而言,如果我想指定一些固定精度的數字,我通常會使用某種定點符號(整數+除數)。

#include <cmath> 

template<class T> 
static T Round(T a) 
{ 
    static_assert(std::is_floating_point<T>::value, "Round<T>: T must be floating point"); 

    return (a > 0) ? ::floor(a + static_cast<T>(0.5)) : ::ceil(a - static_cast<T>(0.5)); 
} 

template<class T> 
static T Round(T a, int places) 
{ 
    static_assert(std::is_floating_point<T>::value, "Round<T>: T must be floating point"); 

    const T shift = pow(static_cast<T>(10.0), places); 

    return Round(a * shift)/shift; 
} 

int main() 
{ 
    auto x = -1000.123; 
    auto result = Round(x, 3); 
} 

對於double的結果是1000.123000000,其中float是1000.12299。

0
float roundoff(float value, unsigned char prec) 
{ 
    float pow_10 = pow(10.0f, (float)prec); 
    return round(value * pow_10)/pow_10; 
} 

請記住,在某些情況下,由於浮點數在內存中的表示方式,結果並不總是精確的。

相關問題