C语言中如何判断变量是否等于多个值?CS50初学者求助
C语言条件判断错误修正(CS50初学者问题)
原代码的核心错误解析
第一版代码问题
strcmp是C标准库中用于比较两个字符串的函数,仅接受两个字符串参数,你错误地将多个比较逻辑通过||塞进了strcmp的参数列表里,导致编译器提示参数数量超标。另外,else if块里还写错了判断条件(误将同意选项Yes/Y加入了拒绝判断)。
第二版代码问题
- 没有定义过名为
str的标识符,你可能混淆了字符串函数的调用形式; - 用单引号
'包裹字符串(如'yes')是错误的——C语言中,单引号用于表示单个字符,字符串必须用双引号"; - 变量名拼写错误:
usename应为username。
修正后的可运行代码
#include <stdio.h> #include <cs50.h> #include <string.h> int main(void) { string username = get_string("What would you like your username to be? "); string agreement = get_string("Do you agree to the following terms & conditions? "); // 对每个同意选项单独调用strcmp,用||连接逻辑判断 if (!strcmp(agreement, "yes") || !strcmp(agreement, "y") || !strcmp(agreement, "Yes") || !strcmp(agreement, "Y")) { printf("You can now continue using the service, %s! \n", username); } // 同理处理拒绝选项,修正之前的条件错误 else if (!strcmp(agreement, "no") || !strcmp(agreement, "n") || !strcmp(agreement, "No") || !strcmp(agreement, "N")) { printf("You need to agree to the terms & conditions to use the service\n"); } else { printf("You need to select an option\n"); } }
简化优化方案(可选)
如果不想重复判断大小写,可以先把输入字符串转成小写(或大写),减少重复判断:
#include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> // 自定义函数:将字符串转为全小写 void str_to_lower(char *str) { for (int i = 0; str[i] != '\0'; i++) { str[i] = tolower((unsigned char)str[i]); } } int main(void) { string username = get_string("What would you like your username to be? "); string agreement = get_string("Do you agree to the following terms & conditions? "); str_to_lower(agreement); // 只需判断小写形式即可覆盖所有大小写输入 if (!strcmp(agreement, "yes") || !strcmp(agreement, "y")) { printf("You can now continue using the service, %s! \n", username); } else if (!strcmp(agreement, "no") || !strcmp(agreement, "n")) { printf("You need to agree to the terms & conditions to use the service\n"); } else { printf("You need to select an option\n"); } }
内容的提问来源于stack exchange,提问作者Korabii
相关产品推荐
相关产品推荐

