这里说两种方法:
1、类型强转实现四舍五入
一个带有小数位的浮点数,加上0.5再强转为int型,即可实现,代码实现:
#include<bits/stdc++.h>
using namespace std;
int main(){
int a1,a2;
double x=1.6,y=1.4;
a1=x+0.5;
a2=y+0.5;
cout<<"a1="<<a1<<endl<<"a2="<<a2<<endl;
return 0;
}
测试结果:
2.运用round()函数实现
用round()时需要包含头文件include<math.h>
#include<bits/stdc++.h>
using namespace std;
int main(){
double x=1.6,y=1.4;
cout<<"a1="<<round(x)<<endl<<"a2="<<round(y)<<endl;
return 0;
}
运行结果: