【发布时间】:2015-08-24 12:34:06
【问题描述】:
我最近开始了 C 的在线课程,并且正在解决 PS1 中的第二个问题。这个问题要求我们要求用户输入以美元为单位的找零,并计算您可以给他们找零的最小硬币数量,前提是您只允许使用 25 美分、10 美分、5 美分和 1 美分的硬币。
例如,50 美分是 2 个 25 美分硬币,65 美分是 2 个 25 美分硬币、1 个 10 美分硬币和 1 个 5 美分硬币。
这是我的代码:
#include <stdio.h>
#include <cs50.h>
int main(void)
{
float change = 0;
int coinCounter = 0;
int remainder = 0;
int remainder1 = 0;
int remainder2 = 0;
int remainder3 = 0;
.
do
{
printf("Please enter the change in dollars: ");
change = GetFloat();
}
while(change <= 0);
//converts amount in dollars to cents
change = change*100;
//We want to use the largest number of big cois as possible to make up the change.
// This calculates the remainder (if any) after dividing the change by 25. % = modulo, only works with integer operands.
remainder = (int)change % 25;
//(change - remainder) gets us the largest number divisible by 25. This line then calculates
// the maximum number of 25cent coins we can use, and sets this number equal to the coinCounter.
coinCounter = ((int)change - remainder)/25;
//Finds the remainder (if any) when dividing the last remainder by 10.
remainder1 = remainder % 10;
//(remainder - remainder1) gets us the largest number divisible by 10. Dividing this by 10, we
// determine the max amount of 10 cent coins we can use to make up the required change. We then add
// this number of coins to the total coinCounter.
coinCounter = coinCounter + ((remainder - remainder1)/10);
//Again, take the remainder (if any) from the last calculation, and find the remainder when dividing by 5.
remainder2 = remainder1 % 5;
// (remainder1 - remainder2)/5 tells us the number of 5 cent coins we need to make up the required change.
// We add the number of coins to the coin counter.
coinCounter = coinCounter + ((remainder1 - remainder2)/5);
//Finds the remainder when dividing last remainder by 1. There will actually be no remainder, so remainder 3 will
// equal zero.
remainder3 = remainder2 % 1;
//Here, (remainder2 - remainder1)/1 Finds the number of 1 cent coins required to make up the left change.
// remainder3 will always be zero. Hence (remainder2)/1 will always be equal to remainder 2. We add this number
// of 1 cent coins to the coinCounter.
coinCounter = coinCounter + ((remainder2 - remainder3)/1);
//We print out coinCounter, which is the smallest number of coins required to make up the change.
printf("%i\n",coinCounter);
}
现在我是编程新手,所以我很清楚可能有更有效的方法来解决这个问题。但是,这似乎工作得很好。然而,奇怪的是,当我尝试“4.2”时,我得到了一个不正确的结果。我应该得到 18 个硬币(16 个 25 美分硬币和 2 个 10 美分硬币),但程序显示 22。它适用于我尝试过的所有其他数字。
我无法弄清楚我做错了什么。我觉得它要么与我通过乘以 100 将美元变为美分有关,要么与我计算模数并将变化转换为 int 有关,但不幸的是我无法单独计算出来。
我已经对我的代码进行了大量注释,因此它更容易理解。我希望有人可以帮助我!
【问题讨论】:
-
哎呀,我想知道
4.2是否不能在float中精确表示,floor(4.2f*100)不是420而是419。但那不可能是原因,因为在stackoverflow上必须有数百个类似问题的答案...... -
您可以使用更多
printf调试单个段落或逐步执行;无论如何,你可以改进你的代码方法 -
我不知道你当然知道,但你应该已经失败了,因为使用货币的浮点变量。整数转换只会让情况变得更糟。