结构体数组:输入10本图书的序号,书名,作者,价格。并输出图书的各项信息和平均值。

#include<stdio.h>

struct book{			//定义结构体
    int id;
    char name[10];
    char editor[10];
    int price;
};
int main(){
    struct book books[10];  //定义结构体数组
    int i,sum=0;
    for(i=0;i<10;i++){
        scanf("%d%s%s%d",&books[i].id,&books[i].name,&books[i].editor,&books[i].price);
        sum+=books[i].price;
    }
    //printf("%d",sum);
    float ave;
    ave=sum/10.0;
    struct book *p;		//定义一个指向book结构体类型的指针变量
    printf("ID\tname\teditor\tprice");
    for(p=books;p<books+10;p++){		
    /*p=book 使p指向结构体数组books中的第一个元素,p+1指向下一个元素
    指向下一个元素指的是数组中的下一个元素,一个数组元素中存储的是包含
    了定义的结构体中的所有元素。*/
        printf("\n%d  \t%s \t   %s\t  %d\n",p->id,p->name,p->editor,p->price);
    }
    printf("\n%.2f",ave);
    return 0;
}

运行结果如图所示:
在这里插入图片描述

若有错误,敬请指出,万分感激!

好的,下面是用 C++ 编写的程序,它可以从键盘输入 5 个学生的信息,包括学生学号、姓名、性别、出生年月及成绩,用结构体数组保存学生的信息,还可以用函数实现结构体数组输入输出及求成绩最高学生的序号: ```c++ #include <iostream> #include <string> using namespace std; struct Student { int id; string name; char gender; string birthday; float score; }; void input(Student students[], int n) { for (int i = 0; i < n; i++) { cout << "请输入第 " << i + 1 << " 个学生的信息:" << endl; cout << "学号:"; cin >> students[i].id; cout << "姓名:"; cin >> students[i].name; cout << "性别:"; cin >> students[i].gender; cout << "出生年月:"; cin >> students[i].birthday; cout << "成绩:"; cin >> students[i].score; cout << endl; } } void output(Student students[], int n) { cout << "学生信息如下:" << endl; for (int i = 0; i < n; i++) { cout << "学号:" << students[i].id << endl; cout << "姓名:" << students[i].name << endl; cout << "性别:" << students[i].gender << endl; cout << "出生年月:" << students[i].birthday << endl; cout << "成绩:" << students[i].score << endl; cout << endl; } } int getMaxScoreIndex(Student students[], int n) { int maxIndex = 0; for (int i = 1; i < n; i++) { if (students[i].score > students[maxIndex].score) { maxIndex = i; } } return maxIndex; } int main() { Student students[5]; input(students, 5); output(students, 5); int maxIndex = getMaxScoreIndex(students, 5); cout << "成绩最高的学生是:" << students[maxIndex].name << endl; return 0; } ``` 在这个程序中,我们首先定义了一个结构体 `Student`,这个结构体包括了学生学号、姓名、性别、出生年月和成绩这 5 个成员变量。 然后,我们定义了 3 个函数,分别是: - `input()`:用于从键盘输入 5 个学生的信息,包括学生学号、姓名、性别、出生年月和成绩,把这些信息保存到一个结构体数组中。 - `output()`:用于把结构体数组中的学生信息输出到屏幕上。 - `getMaxScoreIndex()`:用于求出结构体数组中成绩最高的学生的序号。 最后,我们在 `main()` 函数中调用这 3 个函数,完成了从键盘输入 5 个学生的信息,包括学生学号、姓名、性别、出生年月及成绩,用结构体数组保存学生的信息,要求用函数实现结构体数组输入输出及求成绩最高学生的序号这个需求。 注意,这个程序使用了 `string` 类型来保存学生的姓名和出生年月,这个类型需要 `#include <string>`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值