Printing the correct number of decimal points with cout

前端 未结 12 1494
孤独总比滥情好
孤独总比滥情好 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:30

    setprecision(n) applies to the entire number, not the fractional part. You need to use the fixed-point format to make it apply to the fractional part: setiosflags(ios::fixed)

    0 讨论(0)
  • 2020-11-22 08:32

    With <iomanip>, you can use std::fixed and std::setprecision

    Here is an example

    #include <iostream>
    #include <iomanip>
    
    int main()
    {
        double d = 122.345;
    
        std::cout << std::fixed;
        std::cout << std::setprecision(2);
        std::cout << d;
    }
    

    And you will get output

    122.34
    
    0 讨论(0)
  • 2020-11-22 08:35

    Just a minor point; put the following in the header

    using namespace std;

    then

    std::cout << std::fixed << std::setprecision(2) << d;

    becomes simplified to

    cout << fixed << setprecision(2) << d;

    0 讨论(0)
  • 2020-11-22 08:36

    I had this similar problem in a coding competition and this is how I handled it. Setting a precision of 2 to all double values

    First adding the header to use setprecision

    #include <iomanip>

    Then adding the following code in our main

      double answer=5.9999;
      double answer2=5.0000;
      cout<<setprecision(2)<<fixed;
      cout <<answer << endl;
      cout <<answer2 << endl;
    

    Output:

    5.99
    5.00
    

    You need to use fixed for writing 5.00 thats why,your output won't come for 5.00.

    A short reference video link I'm adding which is helpful

    0 讨论(0)
  • 2020-11-22 08:42

    Simplify the accepted answer

    Simplified example:

    #include <iostream>
    #include <iomanip>
    
    int main()
    {
        double d = 122.345;
        std::cout << std::fixed << std::setprecision(2) << d;
    }
    

    And you will get output

    122.34
    

    Reference:

    • std::fixed
    • std::setprecision
    0 讨论(0)
  • 2020-11-22 08:43
    #include<stdio.h>
    int main()
    
    {
    
     double d=15.6464545347;
    
    printf("%0.2lf",d);
    
    }
    
    0 讨论(0)
提交回复
热议问题