本守则应该换一美元并且运作良好。但是教授说他会随信输入随机数字。它可以正常使用数字,但是当输入一个字母时,会出现无限循环的任何建议吗?
#include <stdio.h>
#include <stdlib.h>
#define amtPaid 1
#define SENTINAL -1
int quarters(int numChange);
int dimes(int numChange);
int nickels(int numChange);
int pennies(int numChange);
int main(void)
{
double amtDue = 0; // how much is paid
while(1){
printf("\nPlease enter the price less than 1 dollar: ");
scanf(" %lg", &amtDue);
int changeReturn = (amtPaid - amtDue) * 100 + 0.5; // convert decimal to whole number
int updated = 0; // remaining change after amt of change
int numberQuarters = quarters(changeReturn); // number of quarters needed
if(changeReturn >= 0 && changeReturn <= 100){ // if changereturn is between 0 and 100 execute code
printf("\nNice!");
printf("\nWe owe you %i cents" , changeReturn);
if(numberQuarters >= 0){ // get and print number of quarters
printf("\nQuarters: %i", numberQuarters);
updated = changeReturn % 25;
}
if(dimes(updated) >= 0){ // get and print number of dimes
printf("\nDimes: %i", dimes(updated));
updated = updated % 10;
}
if(nickels(updated)>= 0){ // get and print number of nickels
printf("\nNickels: %i", nickels(updated));
updated = updated % 5;
}
if(pennies(updated) >= 0){ // get and print number pennies
printf("\nPennies: %i", pennies(updated));
}
}
else if(amtDue == SENTINAL){
break;
}
else {
printf("That does not make sense to me. please type a valid number");
}
printf("\n %g", amtDue);
}
return 0;
}
int quarters(int numChange){
int numQuarters = 0;
numQuarters = numChange / 25;
return numQuarters;
}
int dimes(int numChange){
int numDimes = 0;
numDimes = numChange / 10;
return numDimes;
}
int nickels(numChange){
int numNickels = 0;
numNickels = numChange / 5;
return numNickels;
}
int pennies(numChange){
return numChange;
}
答案 0 :(得分:3)
如果提供的格式说明符与scanf()
的预期值不同,则提供的值不合适,scanf()
将失败,输入中的值将保留缓冲区,将 feed 提供给下一个scanf()
,仅导致连续失败。在这种情况下,您需要在进行下一次输入之前清理输入缓冲区。你可以使用像
scanf()
while( getchar() != '\n' );
清除输入缓冲区。也就是说,int nickels(numChange)
c
(C99
以后int
现在无效。您必须明确地将其设为CKM_AES_CTR
。
答案 1 :(得分:0)