If 语句默认为 true

问题描述 投票:0回答:1

这是我编写的一个简单过程,旨在尝试解决我在使用其他代码时遇到的问题。有人能告诉我为什么 if 语句默认为 true 吗?我读到一些关于 scanf 需要在变量前有一个空格的内容,但我这样做了。

#include <stdio.h>
#include <stdlib.h>

int main(){

char answer;

printf("Y or N ");

scanf(" %c", &answer);

if(answer == 'Y' || 'y'){
   printf("you said yes \n");
}

else if (answer == 'N' || 'n'){
   printf("you said no \n");
}

else {
   printf("sorry, fail \n");
}

return 0;

}

无论我输入 N 或 n 还是任何其他字符或偶数,它都会返回“你说是”。

c if-statement scanf
1个回答
0
投票

问题出在测试逻辑上。

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

该声明并不像您想象的那样有效。由于缺乏更好的表达方式,“y”为您的程序设置了“true”值。

您最可能想要的是这样的比较测试:

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

注意更正,以下是程序的重构版本。

#include <stdio.h>
#include <stdlib.h>

int main()
{

    char answer;

    printf("Y or N ");

    if (scanf("%c", &answer) != 1)
        return 1;

    if((answer == 'Y') || (answer =='y'))
    {
        printf("you said yes \n");
    }

    else if ((answer == 'N') || (answer == 'n'))
    {
        printf("you said no \n");
    }

    else
    {
        printf("sorry, fail \n");
    }

    return 0;

}

以下是终端的一些测试。

craig@Vera:~/C_Programs/Console/ScanTest/bin/Release$ ./ScanTest 
Y or N U
sorry, fail 
craig@Vera:~/C_Programs/Console/ScanTest/bin/Release$ ./ScanTest 
Y or N Y
you said yes 
craig@Vera:~/C_Programs/Console/ScanTest/bin/Release$ ./ScanTest 
Y or N N
you said no 

回顾一下,请注意逻辑“and”和“or”运算符在各种测试(“if”、“while”等)中如何工作。

© www.soinside.com 2019 - 2024. All rights reserved.