【发布时间】:2021-12-04 02:10:07
【问题描述】:
我编写了一个简单的程序,从用户那里获取姓名和数字并将其存储在一个数组中,然后在每个单元格之间进行比较,直到它达到最高等级然后显示它。问题是当它运行时会显示一条消息(分段错误(核心转储))。我真的不知道我的错误是什么。
#include <stdio.h>
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char name[n];
float score[n];
for (int i = 0; i < n; i++) {
printf("\nEnter the name of Student: ");
scanf("%s", & name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i++) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %f by student %s", name[index], score[index]);
}
【问题讨论】:
-
char 只存储一个字符。您需要使用字符串。仔细阅读
-
关于:
printf("\nHighest mark scored is %f by student %s", name[index], score[index]);编译失败!参数 'score' 和 'name' 必须与格式字符串中的输出转换运算符 '%f' 和 '%s' 的顺序相同 -
为了稳健性,关于:
scanf("%s", & name[i]);输入转换 '%s' 需要一个比输入数组长度小 1 的 MAX WIDTH 修饰符。少 1,因为此转换运算符总是将 NUL 字节附加到输入的末尾