Search code examples
c++coutdecimal-point

C++ - Why is my cout code displaying decimals inconsistently?


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


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.