当有人输入大小写字母时,我如何打印无效,因为他们应该只输入0到10之间的浮点数。
我试着这样编写代码
它出了这么大的问题。
#include<stdio.h>
int main()
{
int trial=0;
float judge1=0,judge2,judge3,judge4,judge5;
char a;
printf("\n%90s","Welcome to the constentant score calculator program :)");
printf("\n\n\n\n\n\rKindly enter the constentant score by 5 respected
judges:");
do
{
printf("\n\nScore by JUDGE 1 (0-10):\t");
scanf("%f",&judge1);
if ((judge1>-1)&& (judge1<11) )
printf("The constentant got %.2f from the judge",judge1);
else
printf("\aPlease input a valid score between 0 and 10:");
} while ((judge1<0) || (judge1>10)||(judge1=a>96) && (judge1=a<123)||
(judge1=a<91) && (judge1=a>64));
}好的,这是我的第二个代码
#include<stdio.h>
int main()
{
float judge1;
printf("\n%90s","Welcome to the constentant score calculator program :)");
printf("\n\n\n\n\n\rKindly enter the constentant score by 5 respected
judges:");
printf("\n\nScore by JUDGE 1 (0-10):\t");
scanf("%f",&judge1);
if ((judge1>-1) && (judge1<11))
printf("The constentant got %.2f from the judge",judge1);
else
printf("\aPlease input a valid score between 0 and 10:");
}
}发布于 2018-12-27 23:17:56
当您使用"%f"作为scanf的格式字符串时,它将只读取对浮点类型有效的字符,并在检测到任何其他字符时停止读取。因此,如果有人键入"abc",则不会将任何内容写入judge1,而是将这些字符留在输入缓冲区中以供再次读取。然后,您将陷入无限循环,读取这些相同的字符。
另外,这个表达式没有任何意义:
judge1=a>96>比==具有更高的优先级,因此它相当于:
judge1=(a>96)假设为a分配了一个值,a>96将该值与96进行比较,计算结果为0或1。然后将该值分配给judge1,覆盖从用户读取的内容。假设您打算使用==,这也是没有意义的。在这种情况下,将根据a>96的结果评估judge1==0或judge1==1。因此,只有当judge1为1且a大于96或judge1为0且a小于或等于96时,上述表达式才为真。
另一个问题是a从未被赋值。您的印象似乎是,当您调用scanf("%f",&judge1);时,读取的第一个字符将写入a。没有导致这种情况发生的链接,所以a没有初始化。
相反,您要做的是使用fgets读入一行文本,然后使用strtof读取float。strtof函数接受指针的地址作为第二个参数,让您知道解析在字符串中的什么位置停止。因此,如果该指针没有指向字符串末尾的空终止符(或换行符,因为fgets读取并存储换行符),那么您就知道您读取的是一个非浮点型字符。
float judge1;
char line[100];
char *p;
int invalid_input;
do {
invalid_input = 0;
fgets(line, sizeof(line), stdin);
errno = 0;
judge1 = strtof(line, &p);
if (errno || ((*p != 0) && (*p != '\n')) || (judge1 < 0) || (judge1 > 10)) {
printf("Please input a valid score between 0 and 10:");
invalid_input = 1;
} else {
printf("The constentant got %.2f from the judge\n ",judge1);
}
} while (invalid_input);发布于 2018-12-27 22:54:52
首先,检查scanf的返回值。如果它与项不匹配,它将返回0。然后您可以检查输入的数字是否在范围内:
int r, judge1;
...
r = scanf("%d", &judge1);
if(r != 1)
{
printf("invalid input\n");
while((r = fgetc(stdin)) != EOF && r != '\n');
}
else if((judge1 < 0) || (judge1 > 10))
printf("input out of range\n");
else
printf("valid input\n");发布于 2018-12-27 23:16:57
问题是你有坏的字符卡住在流中。解决方案在这里:scanf fails why?。John Bode建议的做法是使用getchar将其取出。同样,应用建议的检查机制,它应该会起作用。
它没有提供任何东西,它只会扰乱更大的图景。
https://stackoverflow.com/questions/53946669
复制相似问题