在C中比较相同的浮点值 [英] Comparing Same Float Values In C

查看:161
本文介绍了在C中比较相同的浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

浮点数与浮点数比较的奇怪输出

当我试图比较两个相同的 float 值时,它不会在下面的代码中输出相等的值:

  void main()
{
float a = 0.7;
clrscr();
if(a <0.7)
printf(value:%f,a);
else if(a == 0.7)
printf(equal values);
else
printf(hello);
getch();



$ b $ p
$ p

b
$ b

  float a = 0.7; 

使用 double 常量 0.7 创建一个单精度数字(失去一些精度):

  if a == 0.7)

会比较两个 double 精确数字(<$

转换double 0.7时丢失的精度将 a 提升为双精度时,code>到浮点 a 不会重新获得。



如果您将所有 0.7 值更改为 0.7f (强制浮动而不是双),或者如果你只是使一个一个双,它会正常工作 - 我很少使用浮动现在除非我有大量的数组,并且需要节省空间。

你可以看到这个动作:

  #include< stdio.h> 
int main(void){
float f = 0.7; //双转换为浮动
double d1 = 0.7; // double double double
double d2 = f; // float转换为double

printf(double:%.30f\\\
,d1);
printf(double from float:%.30f\\\
,d2);

返回0;





$ b

会输出类似的内容(稍作修改以显示差异):

 双:0.6999999 | 99999999955591079014994 
。从浮子双:0.6999999 | 88079071044921875000000
\_超出这里不同。


Possible Duplicate:
strange output in comparison of float with float literal

When I am trying to compare 2 same float values it doesn't print "equal values" in the following code :

void main()
{
    float a = 0.7;
    clrscr();
    if (a < 0.7)
        printf("value :  %f",a);
    else if (a == 0.7)
        printf("equal values");
    else
        printf("hello");
    getch();
}

Thanks in advance.

解决方案

While many people will tell you to always compare floating point numbers with an epsilon (and it's usually a good idea, though it should be a percentage of the values being compared rather than a fixed value), that's not actually necessary here since you're using constants.

Your specific problem here is that:

float a = 0.7;

uses the double constant 0.7 to create a single precision number (losing some precision) while:

if (a == 0.7)

will compare two double precision numbers (a is promoted first).

The precision that was lost when turning the double 0.7 into the float a is not regained when promoting a back to a double.

If you change all those 0.7 values to 0.7f (to force float rather than double), or if you just make a a double, it will work fine - I rarely use float nowadays unless I have a massive array of them and need to save space.

You can see this in action with:

#include <stdio.h>
int main (void){
    float f = 0.7;    // double converted to float
    double d1 = 0.7;  // double kept as double
    double d2 = f;    // float converted back to double

    printf ("double:            %.30f\n", d1);
    printf ("double from float: %.30f\n", d2);

    return 0;
}

which will output something like (slightly modified to show difference):

double:            0.6999999|99999999955591079014994
double from float: 0.6999999|88079071044921875000000
                            \_ different beyond here.

这篇关于在C中比较相同的浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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