【问题标题】:How do I make a conversion from scientific notation more precise?如何使科学计数法的转换更精确?
【发布时间】:2020-06-12 22:41:44
【问题描述】:

当我尝试将数字从 1e+050 转换为其自然形式时,它会显示 100000000000000007629769841091887003294964970946560 而不是 10000000000000000000000000000000000000000000000这是代码;

#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;
}

【问题讨论】:

  • 一个long double 可能(取决于您的具体环境)不能代表100000000000000000000000000000000000000000000000000。您将需要使用基于十进制的浮点值(即 this 假设编译器支持)或可以处理如此大整数的大整数库,例如 GNU MP 或上面讨论的 Boost 库。
  • @nanofarad:有时可以。如果 double 使用 base2 或 base10,则在 C++ 中未指定。 base2 不能代表它,但是 base10 可以:(
  • @MooingDuck 啊,我不知道作为规范的一部分支持 base-10 浮点数。很高兴知道!
  • 规范定义了十次方格式,但这并不意味着任何有用的实现都支持它。

标签: c++ c++11 scientific-notation


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    VS2015 和 gcc 10.1 的输出是:

    range value is: 1e+50
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-07
      • 2012-06-22
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多