can't print more decimal of pi [duplicate]

2019-03-02 17:15发布

This question already has an answer here:

I have tried to use long double type in my program to print out more digits of pi. But it only shows 5 digits decimal.

Here is my code.

int main(int argc, char** argv) {

    long double pi_18 = acos(static_cast<long double>(-1));
    cout << "pi to 18:" << pi_18 << endl;

    return 0;
}

and this is my output:

pi to 18: 3.14159

How can I fix this problem?

标签: c++ types pi
2条回答
Animai°情兽
2楼-- · 2019-03-02 17:52

Like so:

#include <iomanip>
#include <iostream>

std::cout << std::setw(15) << pi_18 << std::endl;

The width modifier only affects the next formatting operation, so if you want to format multiple numbers, you have to repeat it before every one. Check out the full documentation of format specifiers.

查看更多
时光不老,我们不散
3楼-- · 2019-03-02 17:56

You could use the precision method:

cout.precision(15);

This allows you to define the precision only once. You don't have to repeat it like with std::setw()

For more information see: http://en.cppreference.com/w/cpp/io/ios_base/precision

查看更多
登录 后发表回答