C++ float轉換int,四捨五入

正常的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






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章