gpt4 book ai didi

CS50 PSET1 cash.c : I can't seem to get it to print the value I want. 只是不断重复输入

转载 作者:行者123 更新时间:2023-11-30 16:30:55 25 4
gpt4 key购买 nike

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

问题:

Write, in a file called cash.c in ~/workspace/pset1/cash/, a program that first asks the user how much change is owed and then spits out the minimum number of coins with which said change can be made

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

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

最佳答案

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

  • 您应该使用 return 0;int
    main(void)
    提供返回值
  • while (x >= .10 && x < .25)和 friend 是多余的:你可以只使用 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 在他的评论回复中提到的那样,可能值得考虑一种不使用 float 学的解决方案。

关于CS50 PSET1 cash.c : I can't seem to get it to print the value I want. 只是不断重复输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50852643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com