C语言 If 语句的主体无论输入什么都运行



我有一种感觉,这将是一个非常简单的错误,但是无论我在程序中键入什么字符,"帮助屏幕"仍然会显示。我一直在研究如何修复一段时间,但无法破解它,正如我所说,我有一种感觉,这将是一件非常愚蠢和简单的事情。我对 C 没有太多经验,所以对任何业余错误都表示不满。哪些符号用于赋值,哪些符号用于在 C 中进行比较?(= 和 ==

int initialSelection(){
printf( "                                Welcome to Anagramania!n");
printf( "Please press (s) to start or (h) to view the help screenn");
initialChoice = getchar();
    if (initialChoice = 'h'){ //Display help screen
        system("cls");
        printf( "                                Anagramania Help Screenn");
        printf( "Welcome to Anagramia, created by Toby Cannon. There are three levels of difficulty in this game, easy, medium, or hard! How good do you think you are? Once you start the game you will see some jumbled letters on the screen. You're job is to guess what word these letters have come from! There is 20 words in each game, and you can review your game at the end. n Good luck!n");
            getch(); //wait for user input
            system("cls"); //Clear the console
        }
}

=赋值,所以你的代码所做的是'h'赋值分配给initialChoice,然后测试结果,即值'h'(赋值表达式的值是赋值的值)。这最终会测试为 true,因此执行if的主体。

==是平等比较。所以:

if (initialChoice == 'h'){
// Note -----------^

任何像样的编译器都应该具有"lint"功能,当您执行此操作时会警告您。(在文档中搜索"警告"。

需要看起来像这样: if (initialChoice == 'h'),所以你实际上是在检查左边的表达式是否等于右

边的表达式

最新更新