C/C++--四舍五入的方法

这里说两种方法:
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;
}

运行结果:
在这里插入图片描述

发布了6 篇原创文章 · 获赞 1 · 访问量 141

猜你喜欢

转载自blog.csdn.net/qq_46015269/article/details/105555261
今日推荐