簡體   English   中英

C++中小數點的位數限制

[英]Digit limitation from decimal point in C++

我是 C++ 的新手。 我有一個雙變量double a=0.1239857並且我想將變量a限制為小數點兩位數。 所以a將為0.12 我知道的C ++有最大的回報是更大的功能或最小整數或低於a像小區或地板上。

有沒有實現浮點變量數字限制的函數? 或者如何更改a變量的精度?

您實際上是在嘗試對數字進行四舍五入,還是只是更改其顯示的精度?

對於前者(截斷多余的數字):

double scale = 0.01;  // i.e. round to nearest one-hundreth
value = (int)(value / scale) * scale;

或(根據 jheriko 的回答酌情向上/向下舍入)

double scale = 0.01;  // i.e. round to nearest one-hundreth
value = floor(value / scale + 0.5) * scale;

對於后者:

cout << setprecision(2) << value;

其中setprecision()的參數是小數點后顯示的最大位數。

這將導致小數點后兩位數。

a = floor(a * 100.0) / 100.0;

你想限制變量是什么意思? 值或其格式。 對於該值,您可以使用樓層 + 除法。 就像是:

double a = 0.12123
double b;

b = floor(a * 100) / 100

如果你只想輸出值,你可以做類似的事情

printf("%.3f", a); // Output value with 3 digits after comma

如果要轉換值本身,可以執行以下操作:

a = (int)(a * 1000) / 1000.0f;

請注意,兩者都沒有四舍五入,它們只是截斷了值。

你也可以做這樣的事情:

//This code will ask the user for an input, set the decimal precision to the hundredths place,  and add 4.63 to the inputted variable

int banana;
cin >> banana;
cout << setprecision(2) << fixed << banana + 4.63; 

使用ios_base::precision格式化 i/o。

您可以在流上設置精度,例如

double d = 3.14579;
cout.precision(2);
cout << d << endl;

// Or use a manipulator

#include <iomanip>
cout << setprecision(2) << d << endl;

請注意,當您向這樣的流發送雙精度或浮點數時,它會自動為您舍入(如果您不知道這一點,有時可能會絆倒您)。

實際的舍入解決方案是x = floor(100*x + 0.5) / 100; 假設要舍入的值在變量“x”中。

x = floor(100*x) / 100; 其他人在這里推薦的實際上會將數字截斷為 2dp。

您可以按如下方式編寫自己的函數,它也可以處理小數的舍入錯誤。

double RoundForGivenPrecision(const double dNumber, int iDecimalPlaces)
{
long long multiplier = (long long)pow(10, iDecimalPlaces);
long double value = dNumber < 0 ? (long long)((nextafter(dNumber, -DBL_MAX)*multiplier)-0.5) : (long long)((nextafter(dNumber,DBL_MAX)*multiplier)+0.5);
return value / multiplier;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM