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

猜你喜欢

转载自blog.csdn.net/qq_41856733/article/details/84444479