1

以下是我的 C++ 程序。我想在变量上存储一个长数字,例如 pi,所以我尝试使用 long double。但是当我运行程序时它只显示 3.14159 。如何将完整的浮点数存储到变量中?

#include <iostream>
using namespace std;

int main() {
long double pi;
pi = 3.14159265358979323846264338327950288419716939937510;
cout << "PI = " << pi << endl;
return 0;
}
4

3 回答 3

4

使用流操纵器,很容易:

#include <iostream>
#include <iomanip>

int main()
{

    long double pi;
    pi = 3.14159265358979323846264338327950288419716939937510L; // L for long double literal

    std::cout << "PI: " << std::setprecision(20) << pi;


}
于 2015-07-18T06:42:39.837 回答
3

这里的问题甚至是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
于 2015-07-18T07:42:46.670 回答
1

将值存储在 long double 中没有问题(实际上存在精度问题)。问题在于打印它。

试试这个:

cout << "PI = " << setprecision(40) << pi << endl;

如果您尝试上述方法,您会发现实际打印的值会在小数点后开始丢失精度(我猜是 18-25)。c/c++ 中 long double 的精度是实现定义的。因此,您需要检查系统的最大精度 long double 可以存储。

于 2015-07-18T07:07:33.737 回答