分别实现“图书”类型数组的输入和输出pta
时间: 2025-02-12 11:27:51 浏览: 35
在PTA(程序设计类实验辅助教学平台)上实现“图书”类型数组的输入和输出,可以参考以下步骤:
1. **定义结构体**:首先需要定义一个表示图书的结构体,例如:
```c
struct Book {
char title[100]; // 书名
char author[50]; // 作者
int year; // 出版年份
};
```
2. **输入函数**:编写一个函数来读取多个图书的信息并存储到数组中,例如:
```c
void inputBooks(struct Book books[], int n) {
for (int i = 0; i < n; i++) {
printf("请输入第 %d 本书的信息:\n", i + 1);
printf("书名: ");
scanf("%s", books[i].title);
printf("作者: ");
scanf("%s", books[i].author);
printf("出版年份: ");
scanf("%d", &books[i].year);
}
}
```
3. **输出函数**:编写一个函数来输出数组中的所有图书信息,例如:
```c
void outputBooks(struct Book books[], int n) {
for (int i = 0; i < n; i++) {
printf("第 %d 本书的信息:\n", i + 1);
printf("书名: %s\n", books[i].title);
printf("作者: %s\n", books[i].author);
printf("出版年份: %d\n", books[i].year);
}
}
```
4. **主函数**:在主函数中调用上述输入和输出函数,例如:
```c
#include <stdio.h>
struct Book {
char title[100];
char author[50];
int year;
};
void inputBooks(struct Book books[], int n);
void outputBooks(struct Book books[], int n);
int main() {
int n;
printf("请输入图书的数量: ");
scanf("%d", &n);
struct Book books[n];
inputBooks(books, n);
outputBooks(books, n);
return 0;
}
void inputBooks(struct Book books[], int n) {
for (int i = 0; i < n; i++) {
printf("请输入第 %d 本书的信息:\n", i + 1);
printf("书名: ");
scanf("%s", books[i].title);
printf("作者: ");
scanf("%s", books[i].author);
printf("出版年份: ");
scanf("%d", &books[i].year);
}
}
void outputBooks(struct Book books[], int n) {
for (int i = 0; i < n; i++) {
printf("第 %d 本书的信息:\n", i + 1);
printf("书名: %s\n", books[i].title);
printf("作者: %s\n", books[i].author);
printf("出版年份: %d\n", books[i].year);
}
}
```
通过以上代码,您可以在PTA平台上实现“图书”类型数组的输入和输出功能。更多详细信息和练习题目,请访问 [PTA官网](https://pintia.cn/problem-sets/1864286047671586816/exam/problems/type/6?problemSetProblemId=1864286399758249984&page=0)。
阅读全文
相关推荐















