ndjustin20 ndjustin20 - 3 months ago 9
C Question

Infinite loop in c due to rounding?

The following code is looping infinitely. I believe it may be a rounding issue though not entirely sure.

I am fairly new to C so not sure why I'm getting the infinite looping that I'm getting. The code seems to make sense though keeps looping.

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



int main(void){

float quarter = .25;
int Qtr = 0;
float dime = .10;
int Dm = 0;
float nickel = .5;
int Nck = 0;
float penney = .01;
int Pn = 0;
float change;
float userInput;
float newspaperCost;

do{
printf("How much is the news paper today: \n");
newspaperCost = GetFloat();
printf("Amount Tendered: ");
userInput = GetFloat();
printf("You entered $%2.2f\n", userInput);
change = userInput - newspaperCost;
printf("Change: $%2.2f\n", change);
}

while(newspaperCost <= 0);

while(change > 0){

printf("%f\n", change);

while(change - quarter > 0){

change = change - quarter;
Qtr++;

}

while(change - dime > 0){

change = change - dime;
Dm++;

}

while(change - nickel > 0){

change = change - nickel;
Nck++;

}

while(change - penney > 0){

change = change - penney;
Pn++;


}

}

printf("Your change consists of %d quarters, %d dimes, %d nickels, and %d pennies\n", Qtr, Dm, Nck, Pn);
} //end main

Answer

You have a logic error in the last while loop.

Instead of

while(change - penney > 0){
   change = change - penney;
   Pn++;
}

Use

while(change > 0){
   change = change - penney;
   Pn++;
}