首页 > 解决方案 > CS50 PSET1 cash.c:我似乎无法让它打印出我想要的值。只是一遍又一遍地重复输入

问题描述

这里是初学者,我觉得我离解决这个问题很近了,但是由于某种原因,每当我运行我的代码时,它只是一遍又一遍地要求我输入欠我多少零钱,并且不打印金额硬币

问题:

在 ~/workspace/pset1/cash/ 中名为 cash.c 的文件中编写一个程序,该程序首先询问用户欠了多少零钱,然后吐出可以进行上述零钱的最小硬币数量

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

int main(void)
{
    float x;
    int coin_amount = 0;
    do
    {
        x = get_float("how much change is owed: $");
    }
    while (x < 0);

    while (x >= .25)
    {
        coin_amount += 1;
        x = x - .25;
    }
    while (x >= .10 && x < .25)
    {
        coin_amount += 1;
        x = x - .10;
    }
    while (x >= .05 && x < .10)
    {
        coin_amount += 1;
        x =  x - .05;
    }
    while (x >= .01 && x < .05)
    {
        coin_amount += 1;
        x = x - .01;
    }
    while (x < .01)
    {
        coin_amount = coin_amount;
    }
    printf("I have %i coins to give you in change\n", coin_amount);
}

我做错了什么有什么想法吗?谢谢 :)

标签: ccs50greedy

解决方案


您的解决方案的主要问题是最终while()循环 - 一旦进入 - 就无法退出。但是还有一些其他的小问题:

  • 您应该使用return 0;int main(void)
  • while (x >= .10 && x < .25)和朋友是多余的:你可以只使用while (x >= .10)(因为第二个条件已经在前一个while()循环中得到满足
  • 您可以使用x -= .25代替x = x - .25(不重要且取决于偏好)

牢记这些要点,您可以尝试以下...

#include <stdio.h>

int main(void) {
    float x = 0.0;
    int coin_amount = 0;

    printf("Enter the currency amount: ");
    scanf("%f", &x);
    printf("You entered: %.4f\n", x);

    while (x >= .25) {
        coin_amount += 1;
        x -= .25;
    }
    while (x >= .10) {
        coin_amount += 1;
        x -= .10;
    }
    while (x >= .05) {
        coin_amount += 1;
        x -= .05;
    }
    // Use .00999 instead of .01 due to quirks with floating point math
    while (x >= .00999) {
        coin_amount += 1;
        x -= .01;
    }
    if (x > 0) {
        printf("Ignoring residual value - %.4f ...\n", x);
    }
    printf("I have %i coins to give you in change\n", coin_amount);

    return 0;
}

你没有指定你的get_float()功能是什么,所以我scanf()改用了。

正如 Yunnosch 在他的评论回复中提出的那样,可能值得考虑一个不使用浮点数学的解决方案。


推荐阅读