Printing the correct number of decimal points with cout

前端 未结 12 1612
孤独总比滥情好
孤独总比滥情好 2020-11-22 08:26

I have a list of float values and I want to print them with cout with 2 decimal places.

For example:

10.900  should be prin         


        
12条回答
  •  野性不改
    2020-11-22 08:49

    To set fixed 2 digits after the decimal point use these first:

    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);
    

    Then print your double values.

    This is an example:

    #include 
    using std::cout;
    using std::ios;
    using std::endl;
    
    int main(int argc, char *argv[]) {
        cout.setf(ios::fixed);
        cout.setf(ios::showpoint);
        cout.precision(2);
        double d = 10.90;
        cout << d << endl;
        return 0;
    }
    

提交回复
热议问题