该函数用于验证输入。它会提示用户输入一个数值(大于或等于 0 ),直到满足条件。如果任何字符输入在数字之前或之后,输入将被视为无效。所需的输出是:
Enter a positive numeric number: -500
Error! Please enter a positive number:45abc
Error! Please enter a number:abc45
Error! Please enter a number:abc45abc
Error! Please enter a number:1800
好吧,这似乎很容易:
#include <stdio.h>
main() {
int ret=0;
double num;
printf("Enter a positive number:");
ret = scanf("%.2lf",&num);
while (num <0 ) {
if (ret!=1){
while(getchar()!= '\n');
printf("Error!Please enter a number:");
}
else{
printf("Error!Please enter a positive number:");
}
ret = scanf("%.2lf",&num);
}
}
但是,无论输入类型如何,我的代码都会一直Error!Please enter a number:
输出。有什么建议吗?