使用长双精度
Using long double
本文关键字:双精度 更新时间:2023-10-16
下面是我的c++程序。我想在变量上存储一个长数字,比如pi,所以我尝试使用长双精度。但是当我运行程序时,它只显示3.14159。如何存储完整的浮点数到变量?
#include <iostream>
using namespace std;
int main() {
long double pi;
pi = 3.14159265358979323846264338327950288419716939937510;
cout << "PI = " << pi << endl;
return 0;
}
使用流操纵符很简单:
#include <iostream>
#include <iomanip>
int main()
{
long double pi;
pi = 3.14159265358979323846264338327950288419716939937510L; // L for long double literal
std::cout << "PI: " << std::setprecision(20) << pi;
}
这里的问题是即使long double
也具有有限的精度。考虑这个(C++11
)
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;
int main() {
cout.precision(51);
std::string pi("3.14159265358979323846264338327950288419716939937510");
cout << pi << endl;
cout << stold(pi) << endl;
cout << M_PIl << endl; /// The constant from <math.h>
}
3.14159265358979323846264338327950288419716939937510
3.14159265358979323851280895940618620443274267017841
^ value changes from here (18th decimal place)
3.14159265358979323851280895940618620443274267017841
将值存储在long double中没有问题(实际上存在精度问题)。问题在于打印。
试试这个:
cout << "PI = " << setprecision(40) << pi << endl;
如果您尝试上述操作,您会发现实际打印的值将从开始失去精度在一些小数点后(我猜是18-25)。c/c++中的长双精度是实现定义的。因此,您需要检查系统是否可以存储long double类型的最大精度。
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 正在将csv文件读取为双精度矢量
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 如何在C++中的同一函数中使用字符串和双精度
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 检查是否以特定精度给出双精度
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- C 字符串返回字符串的整数/双精度/长整型值
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何使双精度值的 C++ 和 C# 中的结果相同
- 使用浮点数和双精度数的非常小数字的数学
- 使用 Xcode 将双精度存储在数组C++中
- 在 C++ 中将双精度变量写入二进制文件
- 如何从字符串转换为双精度*
- 为什么我的数组双精度函数不起作用?
- 高精度双精度的 Sprintf 格式化问题
- C++ cout 将双精度对齐到精度 2 并正确对齐
- 将指针数组分配给双精度
- C++如何将字符串逐行转换为双精度
- 长双精度C++是IEEE二进制128的实现吗?