float和double变量的比较 [英] Comparison of float and double variables

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

问题描述

可能显示的文件:结果
  float和double 结果之间差异
  <一href=\"http://stackoverflow.com/questions/1839422/strange-output-in-comparision-of-float-with-float-literal\">strange在浮动的比较输出浮动文字

我使用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.

请告诉我为什么我得到这些奇怪的输出,有什么办法predict在同一处理器上这些输出。怎么也比较在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 ?

推荐答案

它做的方式彩车的内部重新presentation和双打都在计算机中。计算机二进制中存储号码的是基地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.

当你比较花车,它的共同使用一个小量表示在值小的变化​​。例如:

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.

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

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