这道笔试题也是经常遇到的,虽然看起来很简单,但是最好将这类语句写得规范化,这样大有好处。
题目是这样的:
请填写BOOL,float和指针与“零值“比较的if语句
a)BOOL flag 与零值比较的if语句
b)float x 与零值比较的if语句
c)char *p 与零值比较的if语句
答:
a:if(!flag)//flag等于零
if(flag) //flag 不等于零
b:const float EPSILON 0.00001
if((x <= EPSILON) && (x >= -EPSILON) ) //x等于0
if((x >EPSILON) && (x < -EPSILON) ) //x不等于0
c: if(NULL == p) 或 if(NULL != p)
以下是针对float类型的测试代码
#include <stdio.h>
int main(void){
float x1 = 0.00000001;
float x2 = 0.000001;
float x3 = 0.00000109999999999999999999999999999999;
float EPSILON=0.000001;
printf("EPSILON=0.000001\n");
if (x1 == 0.00000)
printf("x1=%f is 0.000000\n",x1);
else printf("x1=%f is not 0.000000\n",x1);
if((x2 <= EPSILON) && (x2 >= -EPSILON))
printf("x2=%f is 0\n",x2);
else printf("x2=%f is not 0\n",x2);
if((x3 <= EPSILON) && (x3 >= -EPSILON))
printf("x3=%f is 0\n",x3);
else printf("x3=%f is not 0\n",x3);
x1 = 0.00000001;
x2 = 0.0000001;
x3 = 0.0000001999999999999999999999999;
EPSILON=0.0000001;
printf("EPSILON=0.0000001\n");
if (x1 == 0.00000)
printf("x1=%f is 0.000000\n",x1);
else printf("x1=%f is not 0.000000\n",x1);
if((x2 <= EPSILON) && (x2 >= -EPSILON))
printf("x2=%f is 0\n",x2);
else printf("x2=%f is not 0\n",x2);
if((x3 <= EPSILON) && (x3 >= -EPSILON))
printf("x3=%f is 0\n",x3);
else printf("x3=%f is not 0\n",x3);
return 0;
}
运行结果:
EPSILON=0.000001
x1=0.000000 is not 0.000000
x2=0.000001 is 0
x3=0.000001 is not 0
EPSILON=0.0000001
x1=0.000000 is not 0.000000
x2=0.000000 is 0
x3=0.000000 is not 0
--------------------------------
Process exited after 0.02413 seconds with return value 21
请按任意键继续. . .
float类型的精度值可以是6位,即0.00001,也可以是7位,即0.0000001
根据以上程序的运行结果来看,选择6位精度值,和选择7位精度值并没有太大区别,看不出孰胜孰劣,但常见的一般是用6位的精度值,可能是因为float的精度为6~7位,但绝对保证的是6位。