取近似值的函数(向上,向下,四舍五入)C++

一、向上取整

ceil(n)
该值大于等于参数,并等于离该值最近的某个整数。

例如:ceil(3.7)=4      ceil(5.2)=6        ceil(1.001)=2

#include<bits/stdc++.h>
using namespace std;
int main() {
	int ans;
	float s;
	while(cin>>s) {
		ans=ceil(s);
		cout<<ans<<endl;
	}
	
	return 0;
}

运行结果: 

 二、向下取整

floor(n)
该值小于等于参数,并等于离该值最近的某个整数。

例如:floor(3.1)=3      floor(5.9)=5        floor(1.99)=1

#include<bits/stdc++.h>
using namespace std;
int main() {
	int ans;
	float s;
	while(cin>>s) {
		ans=floor(s);
		cout<<ans<<endl;
	}
	
	return 0;
}

运行结果: 

 三、四舍五入

round(n)
该值等于离该值最近的某个整数(看十分位,如果小于等于4,小数部分舍去;大于等于5,则将整数部分加一,小数部分舍去)

例如:round(3.9)=4         round(4.2)=4         round(7.4)=7

#include<bits/stdc++.h>
using namespace std;
int main() {
	int ans;
	float s;
	while(cin>>s) {
		ans=round(s);
		cout<<ans<<endl;
	}
	
	return 0;
}

运行结果: 

 当然了,每个函数的括号里也可以写一条语句,例如a/b,i+j等。


好了,那今天就到这里啦,感谢您的支持,有什么不懂的问题也可以写在评论区里,

我们下期再见吧(◕ᴗ◕✿),拜拜(。◕ˇ∀ˇ◕)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值