1

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?

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
A Phototactic Coder
  • 343
  • 2
  • 5
  • 12
  • 1
    acos() accept a double and returns a double so even if you convert your input and output to long double you will never go beyond double precision, because the input is truncated to double precision and the output is a conversion to long double of a double value, use acosl() instead – woggioni Sep 23 '13 at 22:35
  • 1
    @user2318607 - if `acos` is `std::acos` from `` it is overloaded, and `acos((-1)` returns long double. But the function call is better written as `aces(1.0L)`. – Pete Becker Sep 24 '13 at 13:58

2 Answers2

2

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

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

Fat Noodle
  • 105
  • 1
  • 8