问题描述
我目前正在研究CS50现金问题:估算需要支付一些零钱的硬币数量。
Im currently working on the cs50 "cash" problem: estimating the amount of coins needed to pay some change.
例如:$ 0.41欠额= 1个季度,1个角钱,1镍,1美分。
ex: $0.41 owed = 1 quarters, 1 dime, 1 nickel, 1 penny.
但是,当估计所需的硬币数量时,我最终却以美分为代价,我认为这是由于我的错误,因为它似乎总是偏离一分钱或2枚硬币(便士)。
however, when estimating the amount of coins needed i end up being off with the pennies i believe is due to error on my part as it always seems to be off by one or 2 coins (pennies).
我包含了多个printf语句来尝试跟踪我可以做什么,但我似乎无法弄清楚为什么除法是
I have included multiple printf statement to try and track what i could be doing but i can't seem to figure out why the division isn't working.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
// change
float change = get_float("how much change is owed?: ");
int coins = 0;
//reprompt
while (change < 0)
{
change = get_float("how much change is owed?: ");
}
//quarter
float quarter = 0.25;
float quarters = change / quarter;
quarters = (int) quarters;
change = change - (quarters * quarter);
printf("%f quarters\n", quarters);
//dimes
float dime = 0.10;
float dimes = change / dime;
dimes = (int) dimes;
change = change - (dimes * dime);
printf("%f dimes\n", dimes);
//nickels
float nickel = 0.05;
float nickels = change / nickel;
nickels = (int) nickels;
change = change - (nickels * nickel);
printf("%f nickels\n", nickels);
printf("%f in change left change\n", change);
//pennies
float penny = 0.010000;
float pennies = change / penny;
pennies = (int) pennies;
change = change - (pennies * penny);
printf("%f pennies\n", pennies);
//coins
coins = quarters + dimes + nickels + pennies;
printf("%i\n", coins);
//printf("%f\n", change);
}
推荐答案
在您的C实现中,这些行:
In your C implementation, these lines:
float dime = 0.10;
float nickel = 0.05;
float penny = 0.010000;
将 dime
设置为0.100000001490116119384765625,镍
到0.0500000007450580596923828125,便士
到0.00999999977648258209228515625。这导致每个硬币的计算量略有偏差。此外,处理每个硬币后的更改
的计算有舍入误差。
sets dime
to 0.100000001490116119384765625, nickel
to 0.0500000007450580596923828125, and penny
to 0.00999999977648258209228515625. This results in the calculation for each coin being slightly off. Furthermore, the calculations of change
after processing each coin have rounding errors.
要解决此问题,得到<$后c $ c> change 和 get_float
,将其转换为若干美分,
To fix this, after getting change
with get_float
, convert it to a number of cents with:
int cents = roundf(change * 100);
然后使用整数算术执行所有计算。 (包括< math.h>
以获得 roundf
的声明。)
Then perform all calculations with integer arithmetic. (Include <math.h>
to get the declaration of roundf
.)
这篇关于C中带有浮点数的现金分配错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!