为什么我的if条件表达式总是真的

  • 本文关键字:表达式 真的 条件 if c
  • 更新时间 :
  • 英文 :


我一直在努力让函数中的if语句正确求值。我试图让if语句仅在变量等于"Y"或"Y"时计算为true。我刚开始处理字符变量,所以我怀疑我要么错误地将字符存储到变量中,要么以始终正确的方式计算表达式。

我写的代码如下:

#include <stdio.h>
// fuctions
int Greeting(void);
// variables
int return_status;
int main(void)
{
return_status = Greeting();
printf("Return status is %d n", return_status);
return 0;
}
int Greeting(void)
{
char status;
printf("Welcome to the program. Would you like to continue?(Y/N)n");
scanf(" %c", &status);
if (status == 'Y' || 'y') // Problem is probably here
{
printf("You have said %c.n", status);
return 0;
}
else
{
return 1;
}
}

您在这里写的第一个比较是正确的,但您在语句右侧写的表达式不是比较。您可以直接在那里写入表达式"y",因为它与ASCII表中的0不对应,所以它被认为是true,并且在与OR表达式组合时总是给出true结果。

if(status == 'Y' || 'y')

你应该这样改变;

if((status == 'Y') || (status== 'y'))
if((status == 'Y') || (status == 'y')) //Problem is probably here
{
printf("You have said %c.n", status);
return 0;
}

您可以检查类似的字符

是的,问题是"如果";陈述你必须写:

if (status == 'Y' || status == 'y')

应在main((函数中声明变量return_status。

最新更新