怎么能让结果保留跟加数一样的小数位数?
像2.0+2.0=4.0
3.14+1.86=5.00
谢各位帮忙解答一下
#include <iostream>
#include <stdio.h>//调用printf函数
#include <iomanip>//调用fixed和setprecision函数
using namespace std;
int main(){
float a,b,c,d;
a=2.0;
b=2.0;
printf("%.1f \n",a+b);
c=3.14;
d=1.86;
cout<<fixed<<setprecision(2)<<c+d<<endl;
}
有两种方法:
第一种使用stdio.h的printf函数%.1f
建议参考: https://blog.csdn.net/weixin_42859280/article/details/84839726
第二种使用iomanip库的fixed,setprecision函数保留小数点后2位
建议参考:https://blog.csdn.net/Slience_Perseverance/article/details/6816904
以上这两种方法适用于double, float, 和long double