0

I can not figure out why my code is only printing out 1 when I type in .41. Any help would be appreciated.

int main(void){

    /* make change when given a number */
    float change;

    //promt user for a positive number
    do {
        printf("How much change is owed: \n");
        change = get_float();
    } while (change <= 0);

    //make change a floating number like 5 to 500
    int left_over = round(change * 100);

    //hopefully this will make change subtract from the other ints
    do {
        left_over = change / 25;
        left_over++;
    } while(change > 25);

    do {
        left_over = change / 10;
        left_over++;
    } while(change > 10 || change > 25);

    do {
        left_over =  change / 5;
        left_over++;
    } while(change > 5 || change > 10);

    do {
        left_over = change / 1;
        left_over++;
    } while(change > 1 || change > 5);

    printf("coins: %i \n", left_over);

    return 0;
}

2 Answers 2

0

Your main problem is that you have confused your variables. You have the variable left_over, which according to your comments and your code, holds the amount owed in cents.

Now, you also need another variable, let's say coins, that you will initialize to 0, and will hold at the end of your program the total number of coins needed.

In your code, you use the variable left_over for both of these uses, as in your do-while loops, you have left_over++, which should be coins++.

You also use change in the conditions of your do-while loops, but you should instead use left_over, since change is the amount owed in dollars, so it's in float type.

Hope this makes it a little clearer. If you need more help, drop a comment bellow.

Happy Coding!

1
  • 1
    I will try this and keep working on my problems. Thank you for the help. I have seen in other people's code that they had a variable set to 0 but I did not think it was necessary. I will have to study some more for some reason c is just not sticking in my mind. Commented Jul 1, 2017 at 17:11
0

Let's look what happens at the end of your code:

  do{
       left_over = change / 1;
       left_over++;
    }while(change > 1 || change > 5);

  printf("coins: %i \n", left_over);

change is still 0.41 as it was in the beginning. Whatever left_over was before - doesn't matter as you redefine it left_over = 0.41/1 = 0. Then you do left_over++ and get left_over = 1. Then while condition is false so you exit loop and print this 1. And it is 1 for any input < 1.

Note that if it is > 1, like 1.41, you would have infinite loop.

In general, it seems to me that you have a sort of mess with your variables. Make clear for yourself what each variable stands for. What it is in the beginning, how it should be changed in the code, and what it should be the end.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .