浮点数和双变量的比较 [英] Comparison of float and double variables

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

问题描述


可能的重复:

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.

这篇关于浮点数和双变量的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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