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?
Firstly, you should never (unless you come of with a good reason, and "there are 100 cents in one dollar" is not a good reason) use floating point numbers for currency. They can generate rounding error bugs. Use integers instead, and format output later.
And using that, I would do something like this:
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++;
}
}
Here is an example of how to print currency:
int cents = 7334;
printf("$%d.%d", cents/100, cents%100);