浮点数和双变量的比较

问题描述:


可能的重复:

float和double之间的差异

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

我正在使用visual C ++ 6.0,在一个程序中我正在比较float和double变量
例如对于这个程序

I am using visual C++ 6.0 and in a program I am comparing float and double variables For example for this program

#include<stdio.h>
int main()  
{    
    float a = 0.7f;
    double b = 0.7; 
    printf("%d %d %d",a<b,a>b,a==b);
    return 0;
 }  

我得到1 0 0作为输出

I am getting 1 0 0 as output

#include<stdio.h>
int main()  
{    
    float a = 1.7f;
    double b = 1.7; 
    printf("%d %d %d",a<b,a>b,a==b);
    return 0;
 }  

我得到0 1 0作为输出。

I am getting 0 1 0 as output.

请告诉我为什么我会收到这些奇怪的输出,有什么办法可以在同一个处理器上预测这些输出。还有C中的两个变量如何进行比较?

Please tell me why I am getting these weird output and is there any way to predict these outputs on the same processor. Also how comparison is done of two variables in C ?

它与浮点和双精度的内部表示方式有关在电脑里计算机以二进制存储数字为基数2.当以二进制方式存储时,10位数字可能具有重复数字,计算机中存储的精确值不一样。

It has to do with the way the internal representation of floats and doubles are in the computer. Computers store numbers in binary which is base 2. Base 10 numbers when stored in binary may have repeating digits and the "exact" value stored in the computer is not the same.

当您比较浮动数据时,通常使用epsilon来表示值的小变化。例如:

When you compare floats, it's common to use an epsilon to denote a small change in values. For example:

float epsilon = 0.000000001;
float a = 0.7;
double b = 0.7;

if (abs(a - b) < epsilon)
  // they are close enough to be equal.