我最近注册了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);
}发布于 2018-12-02 22:47:21
代码中的这一行:
get_int();什么也不做。get_int将获取并返回一个整数,但是您从未真正将该值放入变量中,这就是输入不会改变程序行为的原因。
也许你想写这样的东西:
n = get_int();发布于 2018-12-05 16:27:27
do while循环总是执行一次,这就是为什么你总是得到4个硬币,然后你也没有将输入值赋给n。
如果n>0,则第一个do while将无限运行,因此将其更改为:
do {
printf("How much change is owed?\n");
n = get_int();
} while (n == 0);下一步,你做的事情会增加到计数,即使它们不应该,下面应该是更好的。
while (n >= 25) {
count++;
n -= 25;
}祝你使用CS50好运,这也是我开始的地方,它很难,但真的能让你学会思考。
https://stackoverflow.com/questions/53581222
复制相似问题