如何使科学记数法的转换更精确?

How do I make a conversion from scientific notation more precise?

本文关键字:转换 何使科      更新时间:2023-10-16

当我尝试将一个数字从 1e+050 转换为其自然形式时,它显示的是100000000000000007629769841091887003294964970946560而不是 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000如何使转换更精确?这是代码;

#include <iostream>
#include <math.h>
#include <stdint.h>
#include <string.h>
#include <iomanip>
using namespace std;
long double range, a, b;
int main(int argc, char** argv) {
range = pow(10,50);
cout << "enter a and b" << endl;
cin >> a >> b;  
cout.setf(ios::fixed); 
if((a >= range)||(b >= range)||(a <= -range)||(b <= -range)){
cout << "the number is too large" << endl;
}
else{
cout << "a+b= " << a + b << endl;
cout << "a-b= " << a - b << endl;
cout << "a*b= " << a * b << endl;
}
cout << range << endl;
return 0;
}

唯一可以用double精确表示的数字是那些可以通过将 +/-2⁵³ 范围内的整数乘以或除以 2 的整数幂来产生的数字。 值 1E22 是 2,384,185,791,015,625 乘以 4,194,304,这是这种形式(请注意,2⁵³ 是 9,007,199,254,740,992(。 比这更大的十次方不是那种形式。

正如其他评论和答案所提到的,双精度不能代表您想要的值(即 1e+50(。但是,如果你只关心这个值的显示,你可以使用std::stringstram以科学格式显示大双精度:

stringstream strRange;
strRange << range;
cout << strRange.str() << endl;

VS2015 和 gcc 10.1 上的输出均为:

range value is: 1e+50