C++ float转换int,四舍五入

时间:2022-10-29 09:43:50

正常的float 转换为 int 的情况是采用去尾巴的方式,也就是说去掉小数点后面的数值。

1.  常规的float 转换为 int  :

例如: 9.34  =  (int) 9   ;  9.99 =  (int) 9  。

#include<stdio.h>
int main()
{
 float i = 9.34;
 float j =  9.99;
 int a, b;
 a = (int) i;
 b = (int) j;
 printf("a = %d\n",a);
 printf("b = %d\n",b);

}

上面的输出结果为: 

  a = 9

  b = 9

2.  float 转换为 int  需要四舍五入提高精度,则基本算法如下:

 在计算是特别要注意正负数的问题,另外要注意round()函数转换后虽然数值小数点后都变为了零,但此时还是float,还需要转换为 int。

#include<stdio.h>
int main()
{
 float zer =  0;
 float i = 9.34;
 float j =  9.99;
 float k = -9.34;
 float m = -9.99;
 int a, b, c, d, e;
 int a1, b1, c1, d1, e1;
a = (int) (i * 10 + 5) / 10; 
b = (int) (j * 10 + 5) / 10; 
c = (int) (k * 10 - 5) / 10; 
d = (int) (m * 10 - 5) / 10; 
e = zer;
 a1 = (int)  round(i)
 b1 = (int)  round(j);
 c1 = (int)  round(k);
 d1 = (int)  round(m);
 e1 = (int) round(zer);
printf("a = %d\n",a); 
printf("b = %d\n",b); 
printf("c = %d\n",c); 
printf("d = %d\n",d); 
printf("e = %d\n",e);
printf("round a1 is %f\n", a1);
printf("round b1 is %f\n", b1);
printf("round c1 is %f\n", c1);
printf("round d1 is %f\n", d1);
printf("round e1 is %f\n", e1);
}
上面的输出结果为:
 

  a = 9

  b = 10

  c = -9

  d = -10

  e = 0

round a1 is 9 

round b1 is 10

round c1 is -9 

round d1 is -10 

round e1 is  0