#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
int count = 0;
float change;
// prompt the user for input
do
{
change = get_float("Change owed: ");
}
while (change <= 0);
int cents = round(change * 100);
while (change >= 25)
{
cents -= 25;
count ++;
}
while (change >= 10)
{
cents -= 10;
count ++;
}
while (change >= 5)
{
cents -= 5;
count ++;
}
while (change >= 1)
{
cents -= 1;
count ++;
}
printf("%i\n", count);
}
如果删除“舍入”功能,然后将硬币替换为0.25 0.10等,则该程序可以运行,但是在某些输入上显示错误的答案。 我什么都没想我是编程新手,但是我觉得这很简单,只是我缺乏智能。
答案 0 :(得分:1)
哦,我的天哪。我可以在这里发誓吗?我好笨!解决方案很简单!问题是:我创建了一个整数“分”,将“变化”值取整。但是在每个分类型的while循环中,我应该写成(change >= 10)
的时候写成(cents >= 10)
,这样四舍五入实际上就发生了。现在,它可以按预期工作!如果有人在此问题集上需要帮助,这是经过更正(并稍有更改)的代码:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
float change;
int count = 0;
int total;
// prompt the user for input
do
{
change = get_float("Change owed: ");
}
while (change <= 0); // ask the user for only positive numbers
//rounds the input and stores the value in the variable "total"
total = round(change * 100);
//loops for each type of coins
while (total >= 25)
{
total -= 25;
count ++;
}
while (total >= 10)
{
total -= 10;
count ++;
}
while (total >= 5)
{
total -= 5;
count ++;
}
while (total >= 1)
{
total -= 1;
count ++;
}
//prints the converted(to int) and rounded value
printf("%i\n", count);
}