解释这种浮点行为 [英] Explain this floating point behavior

查看:116
本文介绍了解释这种浮点行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请解释为什么以下code循规蹈矩件不同的。

Please explain why the following pieces of code behave differently.

#include<stdio.h>
int main(){
 float a=0.1;
 if(a<0.1)
  printf("less");
 else 
  printf("greater than equal");
getchar();
}

输出:大于等于

 #include<stdio.h>
 int main(){
 float a=0.7;
 if(a<0.7)
  printf("less");
 else 
  printf("greater than equal");
getchar();
}

输出:少出乎我的预期。

PS:这不是功课。

PS: This is NOT homework.

推荐答案

您不能在浮点数可靠地使用比较操作。

You cannot use comparison operators on floating point numbers reliably.

比较两个浮点数的一个好方法是有一个门槛的精度是相对于两个浮点数的大小进行比较。

A good way of comparing two floating point numbers is to have a accuracy threshold which is relative to the magnitude of the two floating point numbers being compared.

是这样的:

#include < math.h >
if(fabs(a - b) <= accurary_threshold * fabs(a))

好阅读:

  • What Every Computer Scientist Should Know About Floating-Point Arithmetic
  • Comparing Floating Point Numbers

这篇关于解释这种浮点行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆