c++如何四舍五入,保留到小数点后指定位数

1. “/”除法运算取整

cout << "9/10 " << 9/10 << endl;//结果为0
double a = 9 / 10;//a=0.0
cout << "9.0/10 " << 9.0/10 << endl;//结果为0.9

2.强制转换

	int a = (int)9.8;//结果a=9
	int b=int(-9.8)//b=-9

3.round(),返回整型值

对绝对值四舍五入,取值不受正负号影响

round(1.5)//返回2
round(1.4)//返回1
round(-1.2)//返回-1
round(-1.5)返回-2

4.保留小数点后指定位数

eg:保留两位            对比了很多资料和方法, round()和pintf()比较简单和万能

(1)printf("%.2f",x)  

#include<bits/stdc++.h>
using namespace std;
int main()
{
   double x=1.11113;
	printf("%.2f",x);
}

(2) round()     先乘,再除

保留两位小数的原理:1.11113*100=111.113;

round(111.113)=111;

111/100=1.11

 aver=round(100*sum/m)/100;

注意:aver一定不能用int ,double或float都行,之前自己愚蠢地犯了这个错误导致输出的一直是整数

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值