I'm just start learning C language
. I wrote this C code to implement Greedy algorithm
I don't know what mistake I've made with this code, that code seems fine but its not working as I expected. Can anybody help me to fix this code?
int main(void) {
float amount = 0;
int cents = 0;
int count = 0;
int amount_left = 0;
amount = .30;
cents = (int)round(amount * 100);
printf("%d", cents);
amount_left = cents;
while (cents - 25 >= 0) {
count = count + 1;
amount_left = cents - 25;
}
while (amount_left - 10 >= 0) {
count = count + 1;
amount_left = amount_left - 10;
}
while (amount_left - 5 >= 0) {
count = count + 1;
amount_left = amount_left - 5;
}
while (amount_left - 1 >= 0) {
count = count + 1;
amount_left = amount_left - 1;
}
printf("You get %d coins\n", count);
}
Notes about the problems in the code:
cents
when there would beamount_left
, in the case of the first loop if it require more that one iteration, the result would be incorrect.amount_left - 10 >= 0
byamount_left >= 10
.printf
statement most probably (by the text) is for printing the count of coin gained by the amount provided.Code:
Using the formula:
initial_amount
=coin value
*coin used
+amount_left
This could be write in C as:
initial_amount
/coin value
=coin used
initial_amount
%coin value
=amount_left
More optimized solution:
Notes:
while loop
operation17 / 5 = 3
in integers arithmetic inC
and17 % 5 = 2
.N
,amount / N
coins count (could be 0, eg:amount = 9
andN = 10
,9/10 = 0
in integer division) and the amount left isamount % N
.amount = 0
.I agree with NetVipeC's answer.
I would add a note that is probably out of your assignment's scope, but might help you create better code in the future:
Your code suffers from code duplication. To eliminate that, I would create a function and call that function several times with different arguments. This process is called code reuse. code reuse is neccesary for writing more complicated programs. Code:
I know this code might look wierd now. I've used a few key features of the
C language
that you will probably learn soon:user-defined function
,array
andfor loop
.Hope this helps. Best of luck with your studies!
Edit:
If you don't wanna use a user-defined function, you can avoid code duplication without it. Basically you just pour the function's content inside the main function (and change names of variables):