gpt4 book ai didi

c - 如何防止 scanf 失败的无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:17 25 4
gpt4 key购买 nike

该守则应该以一美元的价格进行更改并且工作正常。但是教授说他将输入随机数和字母。它适用于数字,但当输入字母时会出现无限循环,有什么建议吗?

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

最佳答案

如果使用 scanf() 提供格式说明符的预期值以外的不适当值,则 scanf() 将失败并且不适当的值将 < em>保留 在输入缓冲区中,为下一个 scanf() 提供 feed,只会导致连续失败。在这种情况下,您需要在进行下一次输入之前清理 输入缓冲区。你可以使用类似的东西

  1. 检查scanf()的返回值
  2. 如果失败,使用 while( getchar() != '\n' ); 清理输入缓冲区。

也就是说,int nickels(numChange) 现在在 c(C99 之后)中无效。您必须明确地将其设为 int

关于c - 如何防止 scanf 失败的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32594465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com