c - 优化 C 中的多个 if else 语句
问题描述
代码:
#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);
推荐阅读
- c# - ASP.NET app upgrade from SSAS 2014 to SSAS 2017 - can't log in from remote PC
- wso2esb - Does WSO2 have a OPCUA connector?
- javascript - 尝试使用“$expr”和 find() 在 mongoose 中“分组”时出错
- java - URL 中的复制服务器名称
- elasticsearch - 整个对象为 'geo_point'
- deep-learning - Pytorch CPU 和 GPU 并行运行
- python-2.7 - 如何使用 mxnet 创建 3D 卷积神经网络?
- html - 使用离子选择动态
- node.js - Angular AOT - UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:#):TypeError:无法读取未定义的属性“请求”
- c# - 存储过程不接受整数参数