向上取整函数: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;
}