写题时,代码中的一个 while 语句里出现了无限循环
当输入一个非数字如“fifty”时,while 中的 scanf 还没有输入,就一直出现“The Target weight: Error!”
应该是哪里出错了呢
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
double w; // input the target weight
int check; // check the return value of scanf
char c;
printf("Enter the Target Weight in lbs: ");
check = scanf("%lf%c", &w, &c);
// represent weight by available disks -- handle incorrect input
double dec; // dec is the decimals part of w
int check1, mark=0; // check1 is a mark used to check if w is a pure number
while (1)
{
if (check == 0 || !isspace(c)){ // Incorret: input is not a pure number
check1 = 0;
}
else { // Incorrect: input can't be represented by available disks
check1 = 1;
dec = w-(int)w;
if (dec==0.25 || dec==0.5 || dec==0.75 || dec==0){
mark=1;
}
else{
mark=0;
}
}
if (check1==0 || w<=0 || w>10000 || mark==0){
printf("Error!\n");
printf("The Target Weight: ");
check = scanf("%lf%c", &w, &c);
}
else {
;
}
}
return 0;
}