gpt4 book ai didi

c - 如何打印字母无效

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

当有人输入大字母或小字母时,我如何打印无效,因为据说他们只输入 0 到 10 之间的 float 。

我试过这样编码

事情就这样错了。

#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:");
}
}

最佳答案

当您使用 "%f" 作为 scanf 的格式字符串时,它将只读取对浮点类型有效的字符,如果出现以下情况将停止读取它检测任何其他字符。因此,如果有人键入“abc”,什么 都不会写入 judge1,并且这些字符会留在输入缓冲区中以供再次读取。然后,您将陷入无限循环,阅读这些相同的字符。

此外,这个表达式没有意义:

judge1=a>96

> 的优先级高于==,所以它等价于:

judge1=(a>96)

假设 a 被分配了一个值,a>96 将该值与 96 进行比较,计算结果为 0 或 1。然后将此值分配给 judge1 ,覆盖从用户那里读取的内容。假设您打算使用 == 这也没有意义。在这种情况下,根据 a>96 的结果评估 judge1==0judge1==1。所以上面的表达式只有在 judge1 为 1 且 a 大于 96 或 judge1 为 0 且 a 小于或等于 96。

另一个问题是a 从未被赋值。您的印象似乎是,当您调用 scanf("%f",&judge1); 时,读取的第一个字符被写入 a。没有导致这种情况发生的链接,因此 a 未初始化。

您要做的是使用 fgets 读取一行文本,然后使用 strtof 读取 floatstrtof 函数接受一个指针地址作为第二个参数,让您知道解析在字符串中的何处停止。因此,如果此指针不指向字符串末尾的空终止符(或换行符,因为 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);

关于c - 如何打印字母无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53946669/

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