c - 无论输入是什么,If 语句的主体都会运行

标签 c if-statement

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

int initialSelection(){
printf( "                                Welcome to Anagramania!\n");
printf( "Please press (s) to start or (h) to view the help screen\n");
initialChoice = getchar();
    if (initialChoice = 'h'){ //Display help screen
        system("cls");
        printf( "                                Anagramania Help Screen\n");
        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'初始选择,然后测试结果,即值'h'(赋值表达式的值是被赋值的值)。最终测试结果为 true,因此 if 的主体被执行。

== 是相等比较。所以:

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

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

关于c - 无论输入是什么,If 语句的主体都会运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29623107/

相关文章:

c - C 中 if else 语句的问题

c - OpenMP - 在并行 for 循环中调用外部函数

c - 在 C 中签名到无符号的转换 - 它总是安全的吗?

c - 警告不是编译时常量的函数参数

java - 降低java方法的圈复杂度

c++ - 比较两个整数而不进行任何比较

bash - 具有多个条件的 if 语句

c - GCC 别名在翻译单元之外运行 -AKA- 这甚至是完成这项工作的正确工具吗?

c++ - 检查互联网连接或不断检查互联网连接

javascript - imacros javascript 如果其他行为不正常等等