使用长双精度

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类型的最大精度。