【发布时间】:2018-05-18 01:21:22
【问题描述】:
为了学校,我要编写一个 C 程序,它需要一些现金并返回达到该金额所需的最少硬币数量。我不知道我做错了什么。我一直在调整和尝试各种不同的东西,但我似乎无法完全调试程序。
程序对某些输入给出了正确的答案,但夸大了许多输入所需的硬币数量。
这是我目前所拥有的。
#include <stdio.h>
int main()
{
float cash;
int n;
int counter=0;
int quarters=0;
int dimes=0;
int nickels=0;
int pennies=0;
for (;;)
{
printf("Enter change amount: ");
scanf("%f",&cash);
if (cash > 0)
{
break;
}
}
n = cash * 100;
counter = 0;
while (n > 0)
{
while (n >= 25)
{
counter ++;
n = n - 25;
quarters ++;
printf("%i\n",n);
}
while (n >= 10 && n < 25)
{
counter ++;
n = n - 10;
dimes ++;
printf("%i\n",n);
}
while (n >= 5 && n < 10)
{
counter ++;
n = n - 1;
nickels++;
printf("%i\n",n);
}
while (n > 0 && n < 5)
{
counter ++;
n = n - 1;
pennies ++;
printf("%i\n",n);
}
}
printf("%d\n",counter + n);
printf("%i quarters, %i dimes, %i nickels, %i pennies\n",
quarters, dimes, nickels, pennies);
return 0;
}
【问题讨论】:
-
为什么使用 while 循环作为 if 语句?另外,你忘了格式化你的结束
} -
你的镍币循环减少了 1 而不是 5。
-
您可以使用 n 来查找所有硬币值,而不是所有的循环,例如“ Quarters = n / 25; n = n % 25;”对每个硬币都这样做。所以对于 136, Quarters = 136 / 25 是 5,n = 136 % 25 是 11。然后你就做剩下的了。
-
从风格上讲,您不应该将递增或递减运算符与递增或递减的变量分开。你真的不需要在一角钱循环中使用
< 25条件;在满足条件之前,您不会达到它。
标签: c while-loop counter nested-loops