while循环不会终止 - 浮算术 [英] while loop does not terminate - float arithmetic

查看:129
本文介绍了while循环不会终止 - 浮算术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C程序正在与浮点值,下面是我的code。

I am working on C program with float values, below is my code.

#include<stdio.h>
#include<stdlib.h>
#include<float.h>   

int main()
{
    int counter = 0;
    float quarter = 0.25;
    float dime = 0.10;
    float nickel = 0.05;
    float penny = 0.01;

    float change = 0.00;

    printf("hi, how much do i owe u?\t");
    scanf("%f", &change);

    while(change > 0.0)
    {
        if(change >= quarter)
        {
            change -= quarter;
            printf("quarter %.2f\n", quarter);
        }
        else if(change >= dime)
        {
            change -= dime;
            printf("dime %.2f\n", dime);
        }
        else if(change >= nickel)
        {
            change -= nickel;
            printf("nickel %.2f\n", nickel);
        }
        else if(change >= penny)
        {
            change -= penny;
            printf("penny %.2f\n", penny);
        }

        counter++;  
    }

    printf("your count is %i\n", counter);

    return 0;
}

输出是:

hi, how much do i owe u?    .45
quarter 0.25
dime 0.10
nickel 0.05
penny 0.01
penny 0.01
penny 0.01
penny 0.01
`^C`

我要preSS CTRL C 终止循环

最后的printf(你的计数%I \\ N,计数器); 根本不执行 - 以硬币计数的#使用

Last printf("your count is %i\n", counter); does not execute at all - to count # of coins used

如果我更换浮动 INT 键入它的工作原理确定。

If i replace float type with int it works OK.

请帮助解决这个问题。

推荐答案

在你的循环的开头添加这样的:

Adding this at the beginning of your loop:

if (change < penny) {
    printf("remaining: %.10f\n", change);
    break;
}

会发出这样的输出:

Will issue this output:

hi, how much do i owe u?        .45
quarter 0.25
dime 0.10
nickel 0.05
penny 0.01
penny 0.01
penny 0.01
penny 0.01
remaining: 0.0099999849
your count is 7

这由内部浮点数重新presentation引起的。有一种内在的错误 - 最浮点数没有一个确切的再presentation - 他们只是真的很好接近

This is caused by the internal float numbers representation. There's an intrinsic error - most float numbers do not have an exact representation - they're just really good approximates.

这篇关于while循环不会终止 - 浮算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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