Search code examples
c++decimalprecisioniomanip

I use the value a, b, c, d to derive the value of e. How can I set a, b, c, d to four decimal places whereas e to one decimal place?


The code below is to display the value of a,b,c,d to four decimal places and the value of e to one decimal place. However, when I run the function, all five variables are in one decimal place. Can you tell me what's wrong with my code and how can I fix it?

#include <iomanip>
#include <algorithm>
#include <vector>

struct Record{
    int year;
    string name;
    string team;
    double completions, attempts, yards, touchdowns, interceptions, e;
};

void passerRate ()
{
    double a, b, c, d, e;

    //quarterbacks is a vector of struct 
    for (int i = 0; i < quarterbacks.size(); i++){
    Record player = quarterbacks[i];
    a = (player.completions / player.attempts - 0.3) * 5;
    b = (player.yards / player.attempts - 3) * 0.25;
    c = (player.touchdowns / player.attempts) * 20;
    d = 2.375 - (player.interceptions / player.attempts * 25);
    cout << fixed << setprecision(4); // I want to set the precision of a,b,c,d to four decimal places 

    e = (a + b + c + d) / 6 * 100;
    cout << fixed << setprecision(1); //I want to set the precision of e to one decimal place
    quarterbacks[i].e = e;  
}

Solution

  • The line cout << setprecision(4) << fixed; will only affect how decimal values are displayed to the standard output thereafter. Here's two solutions that should help you. If what you want is the numbers themselves to be rounded before they're used in other calculations, the following should work well for you:

    double x = 1.23456;
    double x1 = round(x); // x1 is x rounded to nearest whole number
    double x2 = round(x * 10.0) / 10.0; // x2 is x rounded to nearest tenth
    double x3 = round(x * 1000.0) / 1000.0; // x3 is x rounded nearest thousandth
    

    Otherwise, you can set the standard output's precision between print statements, as follows:

    cout << setprecision(4) << fixed; // cout will now print 4 decimal places
    cout << "a = " << a << endl;
    cout << setprecision(1); // cout will now print 1 decimal place
    cout << "e = " << e << endl;