c - C中的循环。程序中的第一个循环不起作用并且是无限的

标签 c loops cs50

我不明白为什么第一个循环不起作用。即使填充的欠 float 实际上大于 0,这也是一个无限循环。为什么循环不起作用?

#import <cs50.h> 
#import <stdio.h>

int main(void)
{
    float owed = -1 ;

    while (owed < 0) 
    {
        printf("O hai! How much change is owed?\n") ;
        float owed = GetFloat() ;
        owed = owed * 100 ;
    }

    int coins = 0 ;

    while (owed >= 25)
    {
        owed = owed - 25 ;
        coins = coins + 1 ;
    }

    while (owed >= 10)
    {
        owed = owed - 10 ;
        coins = coins + 1 ;
    }

    while (owed >= 5)
    {
        owed = owed - 5 ;
        coins = coins + 1 ;
    }

    while (owed >= 1) 
    {
        owed = owed - 1 ;
        coins = coins + 1 ;
    }

    printf("%i\n", coins) ;
}

最佳答案

你需要改变

float owed = GetFloat() ;

owed = GetFloat() ;

因为您有两个不同范围的。 (您不会更改外部!)

编辑

PS: 您可以更改代码:

while (owed >= 25)
{
    owed = owed - 25 ;
    coins = coins + 1 ;
}

int new_coins = ((int)owed)/25;
coins += new_coins;
owed = owed - 25.0f * new_coins;

关于c - C中的循环。程序中的第一个循环不起作用并且是无限的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35378240/

相关文章:

Ruby 关于循环和字符串相等性

php - 为什么反向循环比正常循环快(包括测试)

C For 循环输出错误(控制可能到达非 void 函数的末尾)

c - 为什么我的程序在某些测试中可以正常工作,而在其他测试中却不能正常工作?

c - C语言小数位数计算错误

java - 如果在每个端点上使用 Java 和 C 进行 XBee API 模式通信,可能会出现问题

c - 正确打印输出

javascript - 当数据库img标签中没有条目时仍然显示空框

c - 在linux上使用C中的open()忽略标有 "%"的注释行

c - 合并排序 - 代码中的错误