浮点数平等检查 [英] floating point numbers equality checking

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

问题描述

使用以下代码:

  #include  

int main(void){
float x;
x =(float)3.3 == 3.3;
printf(%f,x);
返回0;

$ / code>

输出为0.00000

但是当数字3.3被替换为3.5时,

  #include< stdio.h> 

int main(void){
float x;
x =(float)3.5 == 3.5;
printf(%f,x);
返回0;



$ b $ p
$ p $输出是1.0000

为什么在输出中有差异?解决方案您应该明白,在C中,3.3的字面量是double类型的。将double转换为float可能会失去精度,因此3.3F与3.3的比较会产生错误。对于3.5,转换是无损的,因为两者都可以精确地表示,并且比较结果是真实的。

这与(基数10而不是基数2) >

  3.3333333 with 3.3333333333333333(false)
3.5000000 with 3.5000000000000000(true)
pre>

With the following code,

#include <stdio.h>

int main(void){
  float x;
  x=(float)3.3==3.3;
  printf("%f",x);
  return 0;
}

the output is 0.00000

but when the number 3.3 is replaced with 3.5,

#include <stdio.h>

int main(void){
  float x;
  x=(float)3.5==3.5;
  printf("%f",x);
  return 0;
}

the output is 1.0000

Why is there a difference in output?

解决方案

You should understand that in C the literal 3.3 has type double. Converting a double to a float may lose precision, so the comparison of 3.3F with 3.3 yields false. For 3.5 the conversion is lossless since both can be represented exactly and the comparison yields true.

It's somewhat related to (in base 10 instead of base 2) comparing

3.3333333 with 3.3333333333333333  (false)
3.5000000 with 3.5000000000000000  (true)

这篇关于浮点数平等检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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