Mik*_*e55 0 c++ numbers rounding
这是我的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
它最多可以工作6位小数.否则会产生一些奇怪的结果.以下是我用于测试和输出的数字:
测试1轮到7位小数
105.265
52.5689745694
25.6835
452.689785
12.456789877458
Run Code Online (Sandbox Code Playgroud)
产量
105.265
52.5689746
25.6835
-214.7483648
12.4567899
Run Code Online (Sandbox Code Playgroud)
测试1轮到8位小数
与以前相同的数字
产量
-21.47483648
-21.47483648
-21.47483648
-21.47483648
12.45678988
Run Code Online (Sandbox Code Playgroud)
正如其他人所说,对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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1843 次 |
| 最近记录: |