1

我正在尝试构建一个简单的变化计算器。用户输入欠款金额,然后按回车键。他们输入的值应该先乘以 100(这样当我们四舍五入时,数字不会被截断)。四舍五入应该将浮点数转换为整数,然后应该执行所有数学运算(while 循环),最后打印出一个数字,表示给了多少硬币(即有多少四分之一,一角硬币,等等...)代码编译得很好,它提示用户输入一个值,但是当你按下回车键时,什么都没有执行,命令行回到空白。

任何想法我做错了什么?我的猜测是 while 循环中的值没有被转移出循环,因此它们可以在下一个循环中使用。但是我是 C 语言的早期初学者,并且不确定循环的正确规则。我尝试查找 while 循环示例,但没有真正解释如何将值从一个 while 循环传递到另一个循环。如果,事实上,这就是问题所在。谢谢你的帮助。

代码修订:

#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main (void) {

    float change;
    int cents;

    int quarter_count = 0;
    int dime_count = 0;
    int nickel_count = 0;
    int pennies = 0;
    int total_count;

    do
    {
        printf("Enter the amount of change you are owed: ");
        change = GetFloat();
        cents = round(change * 100); 
    }
    while (change < 0);
    return cents;

    int quarter = 25;
    while (cents >= quarter)
    {
        cents = cents - quarter;
        quarter_count++;
    }
    return cents;

    int dime = 10;
    while (cents >= dime)
    {
        cents = cents - dime;
        dime_count++;
    }
    return cents;

    int nickel = 5;
    while (cents >= nickel)
    {
        pennies = cents - nickel;
        nickel_count++;
    }
    return pennies;

    total_count = quarter_count + dime_count + nickel_count + pennies;

    printf("%d\n", total_count);

}  
4

1 回答 1

2

在每个 while 循环之后,您都放置return语句。第一个之后的代码while..loop意味着更少。

同样对于第三个while..loop,您将条件设置为类似while (cents >= nickel)但在 while 循环中您不会更改的值。因此,如果值保持大于等于第三个时的值,cents它将在无限循环中。centwhile..loop

查看我更新的代码。它将执行您可能想要的基本功能

#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main (void) {

    float change;
    int cents;

    int quarter_count = 0;
    int dime_count = 0;
    int nickel_count = 0;
    int pennies = 0;
    int total_count;

    do
    {
        printf("Enter the amount of change you are owed: ");
        change = GetFloat();
        cents = round(change * 100); 
    }
    while (change < 0);


    int quarter = 25;

    while (cents >= quarter)
    {
        cents = cents - quarter;
        quarter_count++;
    }

     if (cents <= 0)
      goto done;

    int dime = 10;
    while (cents >= dime)
    {
        cents = cents - dime;
        dime_count++;
    }

   if (cents <= 0)
      goto done;

    int nickel = 5;

    pennies=cents;

    while (pennies >= nickel)
    {
        pennies = pennies - nickel;
        nickel_count++;
    }

done:
    total_count = quarter_count + dime_count + nickel_count + pennies;

    printf("%d\n", total_count);

    return 0;

}  
于 2014-06-09T05:31:57.363 回答