C++中保留小数点后 2 位数字(四舍五入)打印输出

#include <iostream>
#include <iomanip>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
using std::setprecision;
using std::fixed;
int main() {
    
    

       float a;
       float b;
       cin >> a >> b;
       // cout << fixed <<sqrt(pow(a,2)+pow(b,2))+a+b  << endl;
       // cout << fixed <<a*b/2 << endl;
       cout << fixed <<setprecision(2) <<sqrt(pow(a,2)+pow(b,2))+a+b  << endl;
       cout << fixed <<setprecision(2) <<a*b/2 << endl;
       return 0;
}

用到了两个对象:fixed和setprecision()
前一个是将数字以小数的形式展示,后一个是设置数字的有效字数;
联合在一起就可以表示在小数点后显示多少位,默认是四舍五入的。
参考文章

参考文章2

猜你喜欢

转载自blog.csdn.net/weixin_42224577/article/details/109036471