
灯塔何老师为您分享以下优质知识
在C语言中输入多个成绩可以通过多种方法实现,以下是常见的几种方式:
一、使用数组存储成绩
静态数组
定义固定大小的数组,例如存储50个成绩:
```c
include
int main() {
int scores;
printf("输入50个成绩:n");
for (int i = 0; i < 50; i++) {
scanf("%d", &scores[i]);
}
printf("修改后的成绩为:n");
for (int i = 0; i < 50; i++) {
printf("第%d个成绩为:%dn", i + 1, scores[i]);
}
return 0;
}
```
这种方法简单直接,但需要提前确定成绩数量,且数组大小固定。
动态数组(使用指针)
通过指针操作实现动态输入:
```c
include
int main() {
int *ptr = NULL, *end;
int n = 50;
printf("输入%d个成绩:n", n);
for (ptr = &scores; ptr < &scores[n]; ptr++) {
scanf("%d", ptr);
}
printf("修改后的成绩为:n");
for (ptr = &scores; ptr < &scores[n]; ptr++) {
printf("第%d个成绩为:%dn", ptr - &scores + 1, *ptr);
}
return 0;
}
```
这种方法灵活,但需注意数组边界。
二、使用结构体存储多门课成绩
定义结构体来存储每个学生的多门课成绩:
```c
include
include
define MAX_STUDENTS 100
define NUM_COURSES 3
typedef struct {
int num;
int scores1;
int scores2;
int scores3;
struct student *next;
} Student;
Student *create_student() {
Student *new_student = (Student *)malloc(sizeof(Student));
scanf("%d %d %d", &new_student->
num, &new_student->
scores1, &new_student->
scores2, &new_student->
scores3);
new_student->
next = NULL;
return new_student;
}
int main() {
Student *head = NULL;
int n = 10; // 输入学生数量
printf("输入%d个学生的成绩:n", n);
for (int i = 0; i < n; i++) {
Student *new_student = create_student();
if (head == NULL) {
head = new_student;
} else {
Student *prev = head;
while (prev->
next != NULL) {
prev = prev->
next;
}
prev->
next = new_student;
}
}
printf("学生成绩列表:n");
Student *current = head;
while (current != NULL) {
printf("学号: %d, 课程1: %d, 课程2: %d, 课程3: %dn", current->
num, current->
scores1, current->
scores2, current->
scores3);
current = current->
next;
}
// 释放内存(省略)
return 0;
}
```
这种方法适合存储每个学生的多门课成绩,并支持动态添加学生。
三、其他方法
链表存储
使用链表动态添加成绩节点,适合频繁插入操作:
```c
include
include
typedef struct Node {
int score;
struct Node *next;
} Node;
Node *insert_score(Node head, int score) {
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->
score = score;
new_node->
next = *head;
*head = new_node;
return new_node;
}
void print_scores(Node *head) {
Node *current = head;
while (current != NULL) {
printf("成绩: %dn", current->
score);
current = current->
next;
}
}
int main() {
Node *head = NULL;
int n = 10;
printf("输入10个成绩:n");
for (int i = 0; i < n; i++) {
int score;
scanf("%d", &score);
head = insert_score(&head, score);
}
print_scores(head);
// 释放内存(省略)
return 0;
}
```
链表