方法一:利用c++函数 四舍五入:round()函数 向上取整:ceil()函数 向下取整:floor()函数
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a=1.2;
double b=3.7;
cout<<"a="<<a<<"四舍五入值为:"<<round(a)<<endl;
cout<<"b="<<b<<"四舍五入值为:"<<round(b)<<endl;
cout<<endl;
cout<<"a="<<a<<"向上取整值为:"<<ceil(a)<<endl;
cout<<"b="<<b<<"向上取整值为:"<<ceil(b)<<endl;
cout<<endl;
cout<<"a="<<a<<"向下取整值为:"<<floor(a)<<endl;
cout<<"b="<<b<<"向下取整值为:"<<floor(b)<<endl;
return 0;
}
结果如下:
方法二: 四舍五入:浮点数+0.5,然后转换为int类型 向下取整:直接将浮点数转换为int类型 向上取整:直接将浮点数转换为int类型,在加1
#include <iostream>
using namespace std;
int main()
{
double a=1.2;
double b=3.7;
cout<<"a="<<a<<"四舍五入值为:"<<(int)(a+0.5)<<endl;
cout<<"b="<<b<<"四舍五入值为:"<<(int)(b+0.5)<<endl;
cout<<endl;
cout<<"a="<<a<<"向下取整值为:"<<(int)a<<endl;
cout<<"b="<<b<<"向下取整值为:"<<(int)b<<endl;
cout<<endl;
cout<<"a="<<a<<"向上取整值为:"<<(int)a+1<<endl;
cout<<"b="<<b<<"向上取整值为:"<<(int)b+1<<endl;
return 0;
}
|