浮点变量与零值比较学习用例

今天考试,写错了一题,主要没好好看书。

请写出下列代码编写不符合编程规范之处,并修改。

float f32Result = 0.0;

char *pHead = NULL;

if(f32Result == 0.0)

{

;

}

if(pHead == 0)

{

;

}

改正:

if((f32Result >= -EPSINON) && (f32Result <= EPSINON))

if(pHead == NULL)

第一次看到答案的时候很迷惑,不懂EPSINON这个是什么东西,百度一下,然后做个小例子与总结:

浮点变量与零值比较

  ? 【规则4-3-3】不可将浮点变量用“==”或“!=”与任何数字比较。

  千万要留意,无论是float还是double类型的变量,都有精度限制。所以一定要避免将浮点变量用“==”或“!=”与数字比较,应该设法转化成“>=”或“<=”形式。

  假设浮点变量的名字为x,应当将

  if (x == 0.0) // 隐含错误的比较

  转化为

  if ((x>=-EPSINON) && (x<=EPSINON))

  其中EPSINON是允许的误差(即精度)。

下面是自己写的一个小deamon:

#include <stdio.h>
int main(int argc, char** argv)
{
float test_num1 = 0.2;
float test_num2 = 0.000009;
const float EPSINON = 0.00001;
if((test_num1 >= -EPSINON)&&(test_num1 <= EPSINON))
{
printf("This is a test interval;\n");
printf("-EPSINON to EPSINON interval is [%f]~[%f];\n",-EPSINON,EPSINON);
printf("The test_num1 = [%f];\n",test_num1);
printf("The test_num1 is in the interval.");
}
else
{
printf("This is a test interval;\n");
printf("-EPSINON to EPSINON interval is [%f]~[%f];\n",-EPSINON,EPSINON);
printf("The test_num1 = [%f];\n",test_num1);
printf("The test_num1 is not in the interval.\n");
}


if((test_num2 >= -EPSINON)&&(test_num2 <= EPSINON))
{
printf("\n");
printf("This is a test interval;\n");
printf("-EPSINON to EPSINON interval is [%f]~[%f];\n",-EPSINON,EPSINON);
printf("The test_num1 = [%f];\n",test_num2);
printf("The test_num1 is in the interval.");
}
else
{
printf("This is a test interval;\n");
printf("-EPSINON to EPSINON interval is [%f]~[%f];\n",-EPSINON,EPSINON);
printf("The test_num1 = [%f];\n",test_num2);
printf("The test_num1 is not in the interval.\n");
}
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

漫步act

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值