簡體   English   中英

在C ++中將數字顯式舍入到小數點后7位以上

[英]Explicitly rounding numbers to more than 7 decimal places in C++

這是我的代碼:

double round( char* strNumber, int decPlace);

int main()
{
    int decimal;
         char initialNumber[256];

    cout << "Enter decimal and number " << endl;

    cin >> decimal;
    cin >> initialNumber;

    cout << setprecision (15) << round ( initialNumber,decimal ) << endl;   

return 0;
}

double round( char* strNumber, int decPlace)//
{
    double number = atof(strNumber);
    int temp = ( int ) ( pow(10.0,decPlace) * number + 0.5 );
    double result = ( double ) temp / pow(10.0,decPlace);
    return result;
}

它最多可以保留6個小數位。 否則,會產生一些奇怪的結果。 以下是我用於測試和輸出的數字:

測試1舍入到小數點后7位

105.265

52.5689745694

25.6835

452.689785

12.456789877458

輸出量

105.265

52.5689746

25.6835

-214.7483648

12.4567899

測試1舍入到小數點后8位

與以前相同的數字

輸出量

-21.47483648

-21.47483648

-21.47483648

-21.47483648

12.45678988

就像其他人說的那樣,強制轉換為int不適用於大量對象。 你可以考慮用floor代替,並保持數量的要舍double

#include <cstdlib>
#include <cmath>

double round( char* strNumber, int decPlace)
{
    double number = std::atof(strNumber);
    double expo = std::pow(10.0,decPlace);
    return std::floor( expo * number + 0.5) / expo;
}

int范圍可能比double小; 在許多平台上,其最大值約為20億美元,小於大多數輸入數字的pow(10.0,8) * number數字。

您可以將數字保持為double並使用floor四舍五入為整數:

double temp = floor( pow(10.0,decPlace) * number + 0.5 );
double result = temp / pow(10.0,decPlace);
int temp = ( int ) ( pow(10.0,decPlace) * number + 0.5 );

temp可能是32位。 它可以容納大約20億。 溢出。

在我看來就像溢出 pow(10.0,decPlace) * number是一個很大的數字-太大而無法容納32位整數(這可能是您平台上的int值)。

暫無
暫無

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

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