0

所以我一直在 iTunes U 上学习哈佛 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);

}
4

1 回答 1

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;
      }

是的,即使是最简单的问题也可能未被发现,而带有分号的 for/while 语句就是其中之一(这可能是有意的)。

于 2012-08-07T00:33:49.040 回答