嵌套多个while循环 - CS50 greedy.c less

时间:2017-11-06 23:33:40

标签: c cs50 greedy

我对编程非常陌生,并且难以理解while循环如何可以相互结合使用。

你可以从我的代码中看到我可以增加硬币计数,但我觉得应该使用while循环而不是do-while循环来逐行倒计数总计

也许我使它比需要的更复杂但是多个while循环是计算更改值的最佳方法?

任何提示或提示都非常感谢!

int main(void)
{
printf("O hai! ");

float change;

do
{
    printf("How much change is owed?\n");
    change = get_float();
}
while (change <= 0);

int n = (change * 100);     // multiply change by 100 to get int in cents(n)

int coin = 0;               // new int to represent amount of coins


coin++;
int quart = n - 25;     // subtract 25c from n

coin++;
int dime = quart - 10;  // subtract 10c from quart

coin++;
int nick = dime - 5;    // and so on

coin++;
int penny = nick - 1;   // and so on

penny = 0;              // and this is only here because I had an unused int (penny)


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

1 个答案:

答案 0 :(得分:0)

while循环工作正常。你会希望它超过0,而不是像你现在那样小于或等于,你也不需要定义四分之一/角钱,所有这些,你可以使用if语句,例如if(分左)比硬币更多 - =(这是每次遇到的减少的方式)你减去的价值。尝试进行这些更改,我可以从那里为您提供更多帮助

相关问题