C / C ++-rounding method

Here are two methods:
1. Type forced conversion to rounding
A floating-point number with decimal places, plus 0.5 and then converted to int type, you can achieve, code implementation:

#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;
}

测试结果:

Insert picture description here
2. The use of round () function to achieve the
use of round () need to include the header file 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;
}

operation result:
Insert picture description here

Published 6 original articles · Like1 · Visits 141

Guess you like

Origin blog.csdn.net/qq_46015269/article/details/105555261