我最近参加了EDx.com提供的CS50课程。我目前遇到的问题是greedy.c问题是pset1。我觉得问题是我的do-while循环实际上并没有循环。无论我给出程序的输入,我每次都得到4个硬币。请让我知道我做错了什么。
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
int n = 0;
int count = 0;
int cents = 0;
do
{
printf("How much change is owed?\n");
get_int();
}
while(n > 0);
do
{
count++;
n -=25;
}
while(n >= 25);
do
{
count++;
n -=10;
}
while(n >= 10);
do
{
count++;
n -=5;
}
while(n >= 5);
do
{
count++;
n -=1;
}
while(n >=1);
printf("Here is %i coins\n", count);
}
代码中的这一行:
get_int();
什么也没做。 get_int将获取并返回一个int,但是你实际上从未将该值放在变量中,这就是输入不会改变程序行为的原因。
也许你打算写这样的东西:
n = get_int();
do while循环将始终执行一次,这就是为什么你总是得到4个硬币,然后你也没有将输入值赋给n。
如果n> 0,第一次执行while将无限运行,因此将其更改为:
do {
printf("How much change is owed?\n");
n = get_int();
} while (n == 0);
接下来,即使他们不应该做,也会增加数量,下面应该更好。
while (n >= 25) {
count++;
n -= 25;
}
祝CS50好运,这也是我开始的地方,这很难,但真的让你学习思考。