Syed Iftekharuddin
Syed Iftekharuddin

Reputation: 146

Printing decimal precision upto desiired number in cpp

I have an application I want to print the precision of the calculated prime number up to the desired number. But the number is omitted on the terminal as shown below.

enter image description here

The code I used for this is as

 int  main ()
{
    cout << "Enter the precision for calculation" << endl;
    long num_steps ;
    cin >> num_steps ;
    cout << "Precision = " << num_steps << endl;

    double step;
    double  x=0.0, pi, sum = 0.0;

    cout << "Enter the number of CPU core involved in calculation" << endl;
    int numberOfCpuCore = 0;
    cin >> numberOfCpuCore;

    int i;

    step = 1.0l/( double) num_steps;


        }
    pi = step * sum;
    printf("Pi value = %.10le\n", pi);
return 0;

}

My question is how can I print the precision to the desired number as entered from the command line.

Upvotes: 0

Views: 575

Answers (1)

Parisa.H.R
Parisa.H.R

Reputation: 3893

use iomanip. first add #include <iomanip> and then std::setprecision(num_steps) like this program:

This code was written based on Calculate Pi from Geeks For Geeks.

#include <cstdio>
#include <iostream>
#include <iomanip>
using namespace std;

int  main()
{
// Initialize denominator
    double  k = 1;

// Initialize sum
    double  s = 0;

    for (auto i(0); i < 10000; i++)
    {
        if (i % 2 == 0)
        {
            s += 4 / k;
        }
        else
        {
            s -= 4 / k;
        }

// denominator is odd
        k += 2;
    }

    cout << "Pi value =" << std::setprecision(k) << s << endl;

// printf("Pi value = %.10le\n", pi);
    return 0;
}

This will be the output:

enter image description here

Upvotes: 1

Related Questions