C++ 对小数取整和四舍五入函数

向上取整函数:ceil
向下取整函数:floor
四舍五入函数:round

直接上代码

#include <iostream>
#include <string>
#include <cmath>

using namespace std;


//向上取整函数:ceil
//向下取整函数:floor
//四舍五入函数:round

void test() {
	int a = 10;
	int b = 20;
	int c = 3;

	cout << ceil(5.1) << endl;	//6
	cout << floor(5.9) << endl;	//5
	cout << round(5.1) << endl;	//5
	cout << round(5.9) << endl;	//6

	cout << "原始结果: " << endl;
	cout << a * 1.0 / c << endl;	//3.33333
	cout << b * 1.0 / c << endl;	//6.66667

	cout << "使用函数后的结果: " << endl;
	//向上取整
	cout << ceil(a*1.0 / c) << endl;	//4
	//向下取整
	cout << floor(a*1.0 / c) << endl;	//3
	//四舍五入
	cout << round(a*1.0 / c) << endl;	//3
	//四舍五入
	cout << round(b*1.0 / c) << endl;	//7
}

int main() {
	test();

	return 0;
}

其实对于小数的四舍五入,可以直接对小数 加0.5 然后再转为整数的操作。直接看代码

#include <iostream>
#include <string>

using namespace std;

void test() {
	int a = 10;
	int b = 20;
	int c = 3;

	cout << "原始结果: " << endl;
	cout << a * 1.0 / c << endl;	//3.33333
	cout << b * 1.0 / c << endl;	//6.66667

	int aa = a * 1.0 / c + 0.5;
	int bb = b * 1.0 / c + 0.5;
	//因为四舍五入是满0.5 加1,如果小数小于0.5,加了0.5之后依然不会+1;
	//而如果小数大于0.5,加了0.5之后,小数部分就大于1了,直接进位
	cout << aa << endl;	//3
	cout << bb << endl;	//7
}

int main() {
	test();

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值