我不明白为什么第一个循环不起作用。即使填充的欠 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/