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


知識點:
1、用a = (int)f;會直接去尾,若要四舍五入可以這么用:a = (int)(f+0.5);
2、浮點數采用 printf(“f = %.0f\n”,f);形式是會四舍五入的
3、floor() ceil()所需頭文件為 #include<math.h>

測試內容見代碼注解:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM