Display number with decimal places instead of whole number

后端 未结 2 1726
轻奢々
轻奢々 2021-01-22 07:12

I have this

double a = 4.0;
double b = 2.0;
double g = a + b;

std::cout << g;

I am getting 6, but I want to get 6.0

相关标签:
2条回答
  • 2021-01-22 07:38

    If you always want one figure after the decimal point regardless of how many digits the answer is, use std::fixed along with std::setprecision

    #include <iomanip>
    
    std::cout << std::fixed << std::setprecision(1) << g;
    
    0 讨论(0)
  • 2021-01-22 07:49

    One way:

    #include <iomanip>
    //...
    std::cout << std::setprecision(2) << g;
    

    This sets the precision of the output to 2 significant figures.

    Edit: as the other answer points out, prepend std::setprecision with std::fixed.

    0 讨论(0)
提交回复
热议问题