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 に答える