Home > OS >  Printing decimal precision upto desiired number in cpp
Printing decimal precision upto desiired number in cpp

Time:05-08

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.

CodePudding user response:

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

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

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;

#pragma omp parallel for reduction( :sum) num_threads(numberOfCpuCore) private(x)

    for (i = 0; i < num_steps; i  )
    {
        x   = (i   0.5) * step;
        sum = sum   4.0 / (1.0   x * x);
// int threadId = omp_get_thread_num();
// printf("Thread index =%i, Pi value in thread = %le\n", threadId, sum);
    }

    pi = step * sum;

    cout << "Pi value =" << std::setprecision(num_steps) << pi << endl;
// printf("Pi value = %.10le\n", pi);

    return 0;
}

this will the output:

enter image description here

  • Related