知识点:
一、用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(); }