c - 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);
}
我做错了什么有什么想法吗?谢谢 :)
解决方案
您的解决方案的主要问题是最终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 在他的评论回复中提出的那样,可能值得考虑一个不使用浮点数学的解决方案。
推荐阅读
- reactjs - React Konva 在兄弟组件之间共享 ref 引发错误
- python - Python 初学者 - 编写文本文件 - 问题:使用 'r+' 打开时不保存信息
- python - 如何对齐数据点和刻度标签?
- database - 如何连接服务器应用程序和客户端应用程序,Qt
- java - mysql jodbc DB Connect 问题 - 命令行应用程序工作正常。在同一个数据库上运行相同代码的 servlet,DriverManager.getConnection 抛出异常
- flutter - 在颤动中以条纹方式付款时出错
- mysql - 有没有办法在mysql更新忽略查询期间找到被忽略的行?
- laravel - Laravel Sanctum Vue.js - 如何检查会话是否过期
- android - 在图像加载之前显示进度条。扑
- postgresql - Docker Compose Postgres 总是以超时或连接被拒绝而结束