I recently developed a simple program designed to take a certain amount of money (in dollars) and determine the least number of coins necessary to fulfill that requirement.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
// prompts for change and assigns variable owed_change that value
float owed_change = -1;
while (owed_change < 0 )
{
printf("How much change is owed?\n");
owed_change = GetFloat();
}
// sets the varialble n_coins to 0
int n_coins = 0;
// repeats until no more change is owed
while (owed_change != 0)
{
/* checks for the biggest coin that can be used and increases
the number of coins by 1 */
if (owed_change >= .25)
{
owed_change -= .25;
n_coins++;
}
else if (owed_change >= .10)
{
owed_change -= .10;
n_coins++;
}
else if (owed_change >= .05)
{
owed_change -= .05;
n_coins++;
}
else
{
owed_change -= .01;
n_coins++;
}
}
printf("%d\n", n_coins);
}
The program works for multiples of .25
but runs forever for any other number. From testing, I have found out that it has something to do with the variable owed_change
being subtracted from and coming to the result of -0
, which satisfies owed_change != 0
. However, from research, I have found out that -0
as a floating point should act as +0
. If so, what else have I done wrong?