Question

I'm working on an app that needs to print an array through cout on one line, and show 2 decimal places. Currently, my code prints the first two items with 2 decimals, then switches to 1.

Here is the code:

cout << "  Inches ";
    cout << showpoint << setprecision(2) << right;
    for (int i = 0; i < 12; i++)
    {
        cout << setw(5) << precipitation[i];
    }
    cout << endl;

And here is the output:

Inches 0.72 0.89 2.0 3.0 4.8 4.2 2.8 3.8 2.7 2.1 1.6 1.0

Can someone please tell me why this change is precision is occurring and what I can do to fix it?

Thanks

Was it helpful?

Solution

You need to use "fixed" mode. In default floating-point mode, precision() sets the number of significant figures to display. In "fixed" mode, it sets the number of places after the decimal. Case in point:

#include <iostream>
using namespace std;
int main(int argc, char **argv) {
    float pi = 3.14;
    cout.precision(2);
    cout << pi << endl;
    cout << fixed << pi << endl;
}

Gives the output:

3.1
3.14

HTH.

OTHER TIPS

If you just add cout << fixed before output statements in addition to showpoint and setprecision, you will get a consistent formatting for all outputs.

See below:

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

int main()
{
    double precipitation[12] = { .72, .89, 2, 3, 4.8, 4.2, 2.8, 3.8, 2.7, 2.1, 1.6, 1 };
    cout << "  Inches ";
    cout << showpoint << fixed << setprecision(2) << right;
    for (int i = 0; i < 12; i++)
    {
        cout << setw(5) << precipitation[i];
    }
    cout << endl;

    return 0;
}

Now, the output will be as bellow:

Inches  0.72 0.89 2.00 3.00 4.80 4.20 2.80 3.80 2.70 2.10 1.60 1.00

I was troubled with this problem too. You need to use 'fixed' to do this.

Refer to this link: C++ setprecision(2) printing one decimal?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top