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

C++ 对小数取整和四舍五入函数,第1张

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

直接上代码

#include 
#include 
#include 

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 
#include 

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;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/568767.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-09
下一篇2022-04-09

发表评论

登录后才能评论

评论列表(0条)

    保存