C++保留小数点后两位(floor&ceil&round)详解
·
C++四舍五入保留小数点后两位
示例
#include <iostream>
using namespace std;
int main()
{
double i = 2.235687;
double j = round(i * 100) / 100;
cout << "The original number is " << i << endl;
cout << "The keep two decimal of 2.235687 is " << j << endl;
system("pause");
return 0;
}
运行结果
函数解析见下面
1、floor函数
功能:把一个小数向下取整
即就是如果数是2.2,那向下取整的结果就为2.000000
原型:double floor(doube x);
参数解释:
x:是需要计算的数
示例
#include <iostream>
using namespace std;
int main()
{
double i = floor(2.2);
double j = floor(-2.2);
cout << "The floor of 2.2 is " << i << endl;
cout << "The floor of -2.2 is " << j << endl;
system("pause");
return 0;
}
运行结果
2、ceil函数
功能:把一个小数向上取整
即就是如果数是2.2,那向下取整的结果就为3.000000
原型:double ceil(doube x);
参数解释:
x:是需要计算的数
示例
#include <iostream>
using namespace std;
int main()
{
double i = ceil(2.2);
double j = ceil(-2.2);
cout << "The ceil of 2.2 is " << i << endl;
cout << "The ceil of -2.2 is " << j << endl;
system("pause");
return 0;
}
运行结果
3、round函数
功能:把一个小数四舍五入
即就是如果数是2.2,那向下取整的结果就为2
如果数是2.5,那向上取整的结果就为3
原型:double round(doube x);
参数解释:
x:是需要计算的数
示例
#include <iostream>
using namespace std;
int main()
{
double i = round(2.2);
double x = round(2.7);
double j = round(-2.2);
double y = round(-2.7);
cout << "The round of 2.2 is " << i << endl;
cout << "The round of 2.7 is " << x << endl;
cout << "The round of -2.2 is " << j << endl;
cout << "The round of -2.7 is " << y << endl;
system("pause");
return 0;
}
运行结果
更多推荐
已为社区贡献6条内容
所有评论(0)