首页 > 解决方案 > 有没有办法将多个范围放在一个 if 语句中

问题描述

我是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..");
}
...

这给出了“错误输入”的结果,无论我输入什么(我输入了 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 语句中编写相同的东西,我觉得这会使我的代码不必要地长...

标签: cif-statementascii

解决方案


你搞砸了关系方向,你也可以使用字符文字。尝试这个

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

推荐阅读