im curently doing pset4, but redoing the psets one by one for practice since I feel like im not yet ready to make pset4. Just finished pset2, Cash. The code is right and works, i was just wondering if there is a way to make it cleaner, or with less lines, since im rewriting alot of stuff that I believe could be done in a much shorter way, mostly in the printf parts. Maybe with a for loop and replacing a variable with the change left after aplying the %? Any tips are really appreciated, thanks!
The code:
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
float change;
int quarter = 25, dime = 10, nickel = 5, penny = 1, sum, sum_two, sum_three, sum_four;
do
{
change = get_float("Change owed: ");
}
while (change < 0);
int cents_change = round(change * 100);
sum = cents_change % quarter;
sum_two = sum % dime;
sum_three = sum_two % nickel;
sum_four = sum_three % penny;
if (sum == 0)
{
printf("%i\n", cents_change / quarter);
}
else if (sum != 0 && sum_two == 0)
{
printf("%i\n", ((cents_change - sum) / quarter) + (sum / dime));
}
else if ( sum != 0 && sum_two != 0 && sum_three == 0)
{
printf("%i\n", ((cents_change - sum) / quarter) + (sum / dime) + (sum_two / nickel));
}
else if ( sum != 0 && sum_two != 0 && sum_three != 0 && sum_four == 0)
{
printf("%i\n", ((cents_change - sum) / quarter) + (sum / dime) + (sum_two / nickel) + (sum_three / penny));
}
}