關於C語言進位問題的小測試(直接去尾or四捨五入)

知識點:
一、用a = (int)f;會直接去尾,若要四捨五入能夠這麼用:a = (int)(f+0.5);
二、浮點數採用 printf(「f = %.0f\n」,f);形式是會四捨五入的
三、floor() ceil()所需頭文件爲 #include<math.h>web

測試內容見代碼註解:svg

#include <stdio.h>
#include<math.h>//floor() ceil()所需頭文件 
void test1()//強制類型 四捨五入進位 
{
	 float f = 1.5; int a;
	 a = (int)(f+0.5); 
	 printf("a = %d\n",a);//2 
}
void test2()//向下取整 
{
	float f = 1.9999; int a; 
	a = floor(f);
	 printf("a = %d\n",a);//1 
}
void test3()//向上取整 
{
	 float f = 1.01; int a;
	 a = ceil(f); 
	 printf("a = %d\n",a);//2 
}
void test4()//直接轉換(去尾) 
{
	float f = 1.9; int a; 
	a = (int)f; 
	printf("a = %d\n",a);	//1 
}
void test_a()//不用強制轉換自己也是直接去尾 
{
	float f = 1.9555; int a=f; 
	printf("a = %d\n",a);//1 
}

void test_b()//這樣操做能作到四捨五入 
{
	float f = 1.9555;
	printf("f = %.0f\n",f);//2 
}
void test_c()///這樣操做也是四捨五入 
{
	float f = 1.9555;  
	printf("f = %5.1f\n",f);// 2.0 
}
int main()
{
	 test1();
	 test2();
	 test3();	 
	 test4();
	 
	 test_a(); 
	 test_b();
	 test_c();
 }
相關文章
相關標籤/搜索