所以我一直在关于iTunes U的Harvard CS50课程,并遇到了一些问题。代码运行然后停止。我解释了代码给我带来麻烦的问题。
// Program calculates the amount of change you can give with the least amount of coins.
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int
main(void)
{
float change = 0, inputflag = 1;
int changeint = 0;
int quarter = 25, dime = 10, nickel = 5, penny = 1; // Coins and values
int qc = 0, dc = 0, nc = 0, pc = 0; // Coin value change (Qc = Quarter Change)
// Prompts user for input and validates.
while (inputflag == 1)
{
printf("How much change? ");
change = GetFloat();
if (change == 0)
{
printf("You have no change!\n");
inputflag = 0;
}
else if (change > 0)
{
printf("%.2f\n", change);
inputflag = 0;
}
else
{
printf("Please enter a non-negative number! \n");
}
}
程序在这里停止。我运行代码,输入一个可接受的值,然后程序停止运行。它不会移动到下面的部分。
我花了最后一个小时来讨论这个问题仍然无法弄清楚是什么让程序无法运行。 inputflag值设置为0,从而打破第一个while循环,然后应该在下面移动if(change!= 0),它不会...所以任何建议都将非常感激。
if (change != 0) // If the change is zero, this section is skipped
{
changeint = round(100 * change);
printf("%d", changeint);
}
// The following four sections subtract coin amount, compare it, and add 1 to count.
while (changeint >= quarter);
{
changeint = changeint - quarter;
qc = qc + 1;
}
while (changeint >= dime);
{
changeint = changeint - dime;
dc = dc + 1;
}
while (changeint >= nickel);
{
changeint = changeint - nickel;
nc = nc + 1;
}
while (changeint >= penny);
{
changeint = changeint - penny;
pc = pc + 1;
}
//Prints output
printf("You owe a total of %d coins!", qc + dc + nc + pc);
}
答案 0 :(得分:6)
每个while
声明第一行的分号都应该受到指责。你应该删除它们以避免不可避免的无限循环:
while (changeint >= quarter)
{
changeint = changeint - quarter;
qc = qc + 1;
}
while (changeint >= dime)
{
changeint = changeint - dime;
dc = dc + 1;
}
while (changeint >= nickel)
{
changeint = changeint - nickel;
nc = nc + 1;
}
while (changeint >= penny)
{
changeint = changeint - penny;
pc = pc + 1;
}
是的,即使是最简单的问题也可能未被发现,而对于带有分号的/ while语句就是其中之一(可能是这样)。