首页 > 解决方案 > 优化 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;
    }

所以基本上这是一个贪心算法。它将所欠现金作为投入,评估最小数量。硬币给。(美国货币)。我认为我的代码中有很多重复。它没有优化。有人可以帮我吗?

标签: cif-statementoptimizationsimplification

解决方案


首先,您永远不应该(除非您有充分的理由,并且“一美元中有 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);

推荐阅读