如何使科学记数法的转换更精确?
How do I make a conversion from scientific notation more precise?
当我尝试将一个数字从 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
相关文章:
- 如何使科学记数法的转换更精确?
- 我写的 ASCII 到二进制转换器C++向后显示二进制,如何使其正确显示?
- 将uintptr_t转换为布尔值会使 SSO 基准速度减慢数倍
- 将运算符<<与隐式转换的非基本数据类型一起使用时出错
- 我需要将阵列样式的邻接矩阵转换为矢量样式(以使其看起来更好)
- 在 C++ 中转换 std::string,使其可以是 C# 中的 byte[]
- 两种类型转换有何不同?
- 如何使转换功能工作?
- 将C++转换为C#:如何包装C++中的类,使模板类中的方法在C#中的派生类中可用
- 将字符串转换为char,当我cout时,它是正确的,但是当我将chdir与char一起使用时,它不起作用
- 如何使转换运算符返回引用和非引用
- 在CV :: MAT和Qimage之间进行转换会使程序崩溃
- 将点云的坐标转换为点云库中的另一个坐标,从而使地平面成为X-O-Y平面?
- 仅通过指针强制转换使类类型可互换,而无需分配任何新对象
- C++,转换字符串,使连续下划线序列变为单个下划线
- Clang:将绑定或mem_fn与字符串::c_str和转换一起使用时出现问题
- 转换递归函数并使其迭代
- 如何使两个模板化的类隐式地相互转换
- 警告:指针和整型之间的比较,传递' read '的参数1使指针的整型没有强制转换
- 从字符串到char[]的转换如何使其变长?