以下代码无限循环。我认为这可能是一个四舍五入的问题,虽然不完全确定。
我对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
答案 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();
这就是你有无限循环的原因。