问题描述
代码:
#include <stdio.h>
int main(void)
{
int coins = 0;
float cash_owed = 0;
printf("Cash owed: ");
scanf("%f",&cash_owed);
while(cash_owed > 0)
{
if(cash_owed >= 0.25)
{
cash_owed -= 0.25;
coins++;
}
else if(cash_owed >= 0.10)
{
cash_owed -= 0.10;
coins++;
}
else if(cash_owed >= 0.05)
{
cash_owed -= 0.05;
coins++;
}
else if(cash_owed >= 0.01)
{
cash_owed -= 0.01;
coins++;
}
}
printf("%i\n",coins);
return 0;
}
所以基本上这是一个贪婪算法。它以所欠现金作为输入,评估最小编号。硬币给。 (美国货币)。我认为我的代码中有很多重复。尚未优化。有人可以帮我吗?
解决方法
首先,永远不要(除非您有充分的理由,并且“一美元中有100美分”不是一个好理由)使用浮点数作为货币。它们会产生舍入错误错误。请改用整数,然后再格式化输出。
然后使用该代码,我将执行以下操作:
int coins = 0;
int cash_owed = 0;
printf("Cash owed (in cents): ");
scanf("%d",&cash_owed);
int coin_type[] = {25,10,5,1};
for(int i=0; i<sizeof(coin_type)/sizeof(coin_type[0]); i++) {
while(cash_owed >= coin_type[i]) {
cash_owed -= coin_type[i];
coins++;
}
}
以下是如何打印货币的示例:
int cents = 7334;
printf("$%d.%d",cents/100,cents%100);
,
不需要逐一增加硬币。如评论所建议,使用整数,而不是浮点数表示货币。
#include <stdio.h>
int main(void)
{
int total_coins = 0;
int cash_owed = 0;
printf("Cash owed in cents: ");
scanf("%d",&cash_owed);
// Coins from largest to smallest.
int coins[4]={25,1};
for(int i=0;i<4;++i){
total_coins+= cash_owed/coins[i];
cash_owed%=coins[i];
}
// cash_owed contains remainder that cannot be paid with the coins.
printf("%d\n",total_coins);
return 0;
}