为什么不是在以下code一== 0? [英] Why is not a==0 in the following code?

查看:177
本文介绍了为什么不是在以下code一== 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
int main( )
{
    float a=1.0;
    long i;

    for(i=0; i<100; i++)
    {
        a = a - 0.01;
    }
    printf("%e\n",a);
}

的结果是:6.59e-07

Result is: 6.59e-07

推荐答案

这是一个二进制浮点数,而不是一个小数一 - 因此你需要期待的舍入误差。看到的基本的这篇文章中部分:

It's a binary floating point number, not a decimal one - therefore you need to expect rounding errors. See the Basic section in this article:

什么每个程序员应该知道关于浮点运算

What Every Programmer Should Know About Floating-Point Arithmetic

例如,值0.01不具有二进制浮点类型$ P ​​$ pcise重新presenation。为了得到一个正确的结果样品中,你将不得不圆形或使用AA十进制浮点类型(见的维基百科):

For example, the value 0.01 does not have a precise represenation in binary floating point type. To get a "correct" result in your sample you would have to either round or use a a decimal floating point type (see Wikipedia):

二元定点类型是最常用的,因为重新缩放操作可以以最快的速度位移位来实现。二进制定点数可以重新两个present分数幂准确,但是,像二进制浮点数字,不能准确地重新十present分数幂。如果十确切的分数幂期望,那么应该使用十进制格式。例如,十分之一(0.1)和百分之一(0.01)可以重新由二进制定点数或二进制浮点重presentations psented只有大约$ P $,而它们可以被重新presented正是在小数定点或十进制浮点再presentations。这些重新presentations可能是连接在许多方面,包括BCD codeD。

Binary fixed-point types are most commonly used, because the rescaling operations can be implemented as fast bit shifts. Binary fixed-point numbers can represent fractional powers of two exactly, but, like binary floating-point numbers, cannot exactly represent fractional powers of ten. If exact fractional powers of ten are desired, then a decimal format should be used. For example, one-tenth (0.1) and one-hundredth (0.01) can be represented only approximately by binary fixed-point or binary floating-point representations, while they can be represented exactly in decimal fixed-point or decimal floating-point representations. These representations may be encoded in many ways, including BCD.

这篇关于为什么不是在以下code一== 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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