下面我的代码哪里错了?
#include<stdio.h>
int mian(void)
{
int age;
char zy,zy1='CS',zy2='EIE',level;
scanf("%d\n",&age);
scanf("%s\n",&zy);
scanf("%s",&level);
if(zy==zy1)
{
if(age<=28)
printf("YES");
else
printf("NO");
}
else if(zy==zy2)
{
if(level=='A' || age>25)
printf("YES");
else
printf("NO");
}
return 0;
}
问大家一个C语言问题,如图所示:
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
3条回答 默认 最新
关注 引自免费微信小程序:皆我百晓生
在你提供的代码中,主要的问题在于
scanf
函数的使用方式和level
变量的数据读取处理上。首先,scanf
函数在读取字符串时,应当使用足够大的字符数组来存储输入的字符串,而你使用了&level
,这实际上是在尝试将整个字符串读入一个单个字符的位置,这是不正确的。此外,当读取含有空格或换行符的输入时,scanf
的行为可能会不符合预期。为了解决这些问题,可以按照以下步骤修改你的代码:
- 使用字符数组来存储专业代号和高校级别,而非单个字符。
- 在读取这些字符串时,确保有足够的空间来存储它们,并且正确地处理可能存在的空格和换行符。
- 确保在条件判断中使用比较运算符
==
而不是赋值运算符=
.
下面是修改后的代码示例:
#include<stdio.h> int main(void) { int age; char major[10], level[10]; // Read the age, major, and level. scanf("%d", &age); // No need for newline character here since we are reading an integer. scanf("%9s", major); // Read up to 9 characters into the major array. scanf("%9s", level); // Read up to 9 characters into the level array. // Convert the major and level strings to uppercase for comparison. // This is optional but can make the code more robust. for(int i = 0; major[i] != '\0'; i++) major[i] = toupper(major[i]); for(int i = 0; level[i] != '\0'; i++) level[i] = toupper(level[i]); // Check the conditions based on the major. if(strcmp(major, "CS") == 0) // Compare the major with "CS". { if(age <= 28) // Check if the age is less than or equal to 28. printf("YES"); else printf("NO"); } else if(strcmp(major, "EIE") == 0) // Compare the major with "EIE". { if(strcmp(level, "A") == 0 || age > 25) // Check if the level is "A" or age is greater than 25. printf("YES"); else printf("NO"); } else { printf("NO"); // Default case: not CS or EIE, so no interview. } return 0; }
在这个修改后的版本中,我们使用了字符数组来存储专业代号和高校级别,通过
strcmp
函数进行字符串比较,并且确保了输入的正确处理。此外,为了简化比较并避免大小写敏感问题,可以将读入的字符串转换为大写。这样,无论用户输入的是大写还是小写,代码都能正确处理。解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 Xsheii7我安装这个文件的时候跳出来另一个文件已锁定文件的无一部分进程无法访问。这个该怎么解决
- ¥15 unity terrain打包后地形错位,跟建筑不在同一个位置,怎么办
- ¥15 FileNotFoundError 解决方案
- ¥15 uniapp实现如下图的图表功能
- ¥15 u-subsection如何修改相邻两个节点样式
- ¥30 vs2010开发 WFP(windows filtering platform)
- ¥15 服务端控制goose报文控制块的发布问题
- ¥15 学习指导与未来导向啊
- ¥15 求多普勒频移瞬时表达式
- ¥15 如果要做一个老年人平板有哪些需求