文章目录
第一题
typedef struct node {
char data;
struct node *lchild, *rchild;
} *BT;
试编写算法函数,形参传入二叉树根结点地址bt以及一个字符变量ch,函数返回二叉树结点data域值等于ch的结点数(若字符ch未包含在二叉树中,函数返回0)。
#include <stdio.h>
typedef struct node {
char data;
struct node *lchild, *rchild;
} *BT;
int cnt(BT root, char ch) {
if (root == NULL) return 0;
return cnt(root->lchild, ch) + cnt(root->rchild, ch) + root->data == ch;
}
第二题
2.编写程序: N名学生的数据存入结构体数组s中,程序功能:把分数最高的学生数据放在b所指的数组中并输出,定义函数int fun (STREC *a,STREC *b),函数功能:函数返回分数最高学生的人数,并把分数最高的学生数据存入数组b中,提示:分数最高的学生可能不止一个(10分)。
要求:
(1) 定义结构STREC描述学生信息(学号(字符串),分数);
(2) 定义函数int fun(STREC *a, STREC *b), 函数功能:函数返回分数最高学生的人数,并把分数最高的学生数据存入数组b中.
(3) 在main函数中调用函数,并输出最高分学生信息:学号,分数。
(4) 按照如下结构编写程序(C语言编程,VC6运行环境)。
......................// 定义结构体STREC描述学生信息
......................// STREC是结构体别名
STREC s[N]={ {"2019005",85}, {"2019003",76},"201902",69}....};
// 学生数据存入数组s,N是学生人数,编写程序时实例数据可不全写
// 采用上述方式
int fun(STREC *a,STREC*b) // 按照该首部, 定义fun函数
{
....................
}
void main(){ //主函数,实现函数fun调用,完成程序的功能
....................
}
答案
#include <stdio.h>
#define N 100
typedef struct {
char number[20]; // 学号
double score; // 分数
} STREC; // 定义结构体STREC描述学生信息, STREC是结构体别名
// 采用上述方式
int fun(STREC *s, STREC *b) // 按照该首部, 定义fun函数
{
//函数功能:函数返回分数最高学生的人数,并把分数最高的学生数据存入数组b中.
int cnt = 0; // 统计最高分的人数
b[cnt++] = s[0];
for (int i = 1; i < N; i++) {
if (s[i].score > b[0].score) {
cnt = 0;
b[cnt++] = s[i];
} else if (s[i].score == b[0].score) {
b[cnt++] = s[i];
}
}
return cnt;
}
void main() { //主函数,实现函数fun调用,完成程序的功能
STREC s[N] = {{"2019005", 85}, {"2019003", 76}, {"2019005", 85}, {"2019005", 85}, {"201902", 69}}; // 学生数据存入数组s,N是学生人数,编写程序时实例数据可不全写
STREC b[N];
int cnt = fun(s, b);
for (int i = 0; i < cnt; i++) {
printf("%s %d\n", b[i].number, b[i].score);
}
}