有没有办法将多个范围放在一个 if 语句中

Is there a way to put multiple ranges in one if statement

我是c语言的新手,堆栈溢出请原谅我的业余错误,如果有...

我试图在我的代码中接受 0 到 9 之间的数字、大写字母和小写字母。所以 ascii 代码在 48-57 或 65-90 或 98-122 之间。还有包含菜单的代码的前一部分。为了简洁起见,我没有包括它。

这是我尝试的第一件事:

int main()
{

char n;

printf("\n\nWhich code will you use?: ");
scanf("%c",&n);

if (n<=57 && n>=57 || n<=65 && n>=95 || n<=98 && n>= 122)
   printf("Binary equivalent..");
                                                             /*there is supposed to be a whole another
                                                              section here.. however i haven't completed 
                                                              that yet. I put a print statement to make 
                                                              sure if the if statement would work...*/
else
   printf("Wrong input..");
}
...

这给出了 "wrong input" 无论我输入什么(我输入了 c、a 和 4)的结果。

我尝试的第二件事是加上括号:

...

if ((n<=48 && n>=57 )||( n<=65 && n>=95 )||( n<=98 && n>= 122))

...

然后我尝试将“%c”更改为“%d”,但也没有任何改变。

...

printf("\n\nWhich code will you use?: ");
scanf("%d",&n);

...

唯一可行的方法是将每个关系分成三个不同的 if 语句。但是我将在每个 if 语句中写同样的东西,我觉得这会使我的代码不必要地长...

你把关系方向搞乱了,你也可以用字符字面量。试试这个

if ((n >= '0' && n <= '9') || (n >= 'A' && n <= 'Z' ) || (n >= 'a' && n <= 'z'))

ASCII 值

位数(0-9):48-57
大写字母(A-Z):65-90
小写字母(a-z):97-122

条件

c >= 48 && c <= 57: true 如果 c 是一个数字
c >= 65 && c <= 90: true 如果 c 是大写字母
c >= 97 && c <= 122: true 如果 c 是小写字母

(c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122):如果 c 是字母数字(字母或数字)

,则为真

但是使用 'a'97 更容易,因为那样你不需要记住整个 ASCII table。

备注

n<=48 && n>=57 将永远是 false。如果您稍等片刻,您会发现没有任何数字(在 ASCII table 或非 ASCII 中)可以同时小于 48 和大于 57