浮子类型的精度 [英] Accuracy of float types

查看:61
本文介绍了浮子类型的精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void main()
{
    float a=0.7;
    if(a<0.7)
    printf("A");
    else
    printf("B");
    getch();
}



如果我在问题答案中输入0.7和0.9的结果是"A",否则每个选项为0.3,0.5,0.6,0.8的结果是"B".为什么会这样?我知道double和float概念.请关注关于这一点,为什么仅在0.7和0.9而不是在其他任何情况下发生.查询仅是这样,如果任何人都可以二进制形式清除它,则将是最有帮助的.

解决方案

十进制整数(精度有限)不一定是二进制整数.

将0.7、0.9和0.3二进制舍入为编译器用于double -s的二进制表示形式的精度.

现在,在您的情况下,问题在于所有带有小数点的数字文字都被编译器视为double.并且double 的精度高于float的精度.

double 常量分配给a变量(类型为float)时,会失去一些精度.
然后将a转换回double(在其尾数上添加伪造的位),以将其与另一个常数进行比较.

尝试将a声明为double,或在常量之后添加"f"(例如0.3f)以使其成为"float" -s.


程序为运行正常,我不知道你为什么感到困惑
因为您已经在一个编译器上设置了>

的值,但我没有尝试过(gcc 3.3和VC ++ 2008).警告级别设置得很高,它不会像C ++那样编译(您为浮点数分配了一个double值),因此可能会给您一些有关编译器和系统上发生的情况的提示.

对于给我一个回答"1"的布偶:您是否编译了原始张贴者代码并设法重现了他的结果?不,不是这样...


void main()
{
    float a=0.7;
    if(a<0.7)
    printf("A");
    else
    printf("B");
    getch();
}



If i m putting 0.7 and 0.9 in the question answer is coming "A".else for every option as 0.3,0.5,0.6,0.8 it is coming "B".Why is it so??I know double and float concept.please focus on that,that why it is happening with 0.7 and 0.9 only and not on any other.query is this only,if any one can clear in binary form then it will be most helpful.

解决方案

Decimal round numbers (with finite precision) are not necessarily binary round numbers.

0.7, 0.9 and 0.3 are binary rounded to the precision of their binary representation used by the compiler for double-s.

Now, in your case, the problem is that all numeric literals having a decimal point are treated by the compiler as double. And the precision of double is more than the precision of float.

When you assign a double constant to your a variable (of type float), you loose some of the precision.
Then you convert a back to double (adding bogus bits to its mantissa) to compare it with another constant.

Try either to declare a as double, or to postfix an "f" after the constants (like 0.3f) to make them "float"-s.


Program is running correctly I dont know why u are confused
as u have already set the value of a


Not on the compilers I''ve just tried it (gcc 3.3 and VC++ 2008) on it''s not. With warning levels set as high as they go it won''t compile (you''re assigning a double to a float) as C++ so that may give you some sort of hint as to what''s happening on your compiler and system.

To the muppet that gave me a "1" for this answer: Have you compiled the original posters code and managed to reproduce his results? No, didn''t think so...


这篇关于浮子类型的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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