0

Not quite sure what the problem is here, but I think it has something to do with my loops. I've been setting up the code a little at a time, adding the sections for each type of coin one at a time. This setup worked fine with just the "quarters" loop, but when I added "dimes", it started giving me strange outputs. For example: if I input ".25", the program outputs "1123926981" as the number of coins needed to make the change. Any ideas on why this is happening and how to debug would be much appreciated.

#include <stdio.h>  
#include <math.h>
#include <cs50.h>

int main(void)
{

float (n);

do
{
    printf("Change Owed:");
    n = GetFloat();
}    
while (n < 0);

n = round(100 * n); int(owed) =  n;

int(coins);
int(quarters);
int(dimes);


while(owed >= 25)
{    
    quarters = owed/25;
    owed = owed % 25;
}    

while(owed >= 10)
{
    dimes = owed/10;
    owed = owed % 10;
}

coins = quarters + dimes;

printf("%d\n",coins);    

}

1 Answer 1

1

This is a good example of what happens when you don't initialize local variables.

If the input is .25, your second while loop never executes and dimes will not be initialized at the time that coins is calculated. As a result, you get "undefined behavior," which in C could mean throwing an error, retrieving a random piece of information from memory, returning a constant – it depends on the compiler, and sometimes on the computer (in the case of random memory access).

Incidentally, a few remarks about your code:

  • You don't need to use parentheses when declaring variables.
  • Avoid putting multiple statements on a single line (n = round(100 * n); int(owed) = n;).
  • Although the code will function correctly, using while in your algorithm for counting coins is misleading, because there's no actual looping; each body is executed either 0 or 1 times.

More reading:

You must log in to answer this question.

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