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;
}
运行结果
到此这篇关于C++详解使用floor&ceil&round实现保留小数点后两位的文章就介绍到这了,更多相关C++ floor ceil round内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关文章