由于四舍五入,c中的无限循环?

时间:2015-07-24 03:57:54

标签: c while-loop floating-point infinite-loop cs50

以下代码无限循环。我认为这可能是一个四舍五入的问题,虽然不完全确定。

我对C很新,所以不确定为什么我会得到无限循环。代码似乎有意义,但保持循环。

#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

3 个答案:

答案 0 :(得分:2)

您在上一个while循环中遇到逻辑错误。

而不是

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

使用

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

答案 1 :(得分:0)

  • 请勿使用浮点表示货币。
  • 除非你有充分的理由,否则不要超过浮动。
  • 便士*
  • 您没有使用任何具有浮点操作数的相等运算符,因此您可能会遇到逻辑错误。

答案 2 :(得分:0)

您的代码:

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

newspaperCost <= 0时不会退出此循环。我假设你没有在

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

这就是你有无限循环的原因。