samedi 26 septembre 2020

Optimize multiple if else statements in C

Code:

#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;
    }

So basically this is a greedy algorithm. It takes cash owed as inputs, Evaluates the minimum no. of coins to give. (US Currency). I think there is so much repeatation in my code. It's not optimized. Can someone help me out here?

Aucun commentaire:

Enregistrer un commentaire