ndjustin20
ndjustin20

Reputation: 105

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

Upvotes: 1

Views: 126

Answers (3)

M. Shaw
M. Shaw

Reputation: 1742

Your code:

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);

Won't exit this loop while newspaperCost <= 0. I'm assuming you aren't inputting a negative number at

  printf("How much is the news paper today: \n");
  newspaperCost = GetFloat();

That's why you have an infinite loop.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206627

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++;
}

Upvotes: 2

Matt Joiner
Matt Joiner

Reputation: 118550

  • Don't use floating point to represent currency.
  • Prefer double over float unless you have a good reason.
  • penny*
  • You're not using any equality operators with floating point operands, so you probably have a logical error.

Upvotes: 0

Related Questions