用c语言建立一个数组类ARR,求一个整型数组所有元素中的最大值及该最大值在数组中的序号(从1开始),具体要求如下: (1)私有数据成员: int n : 数组实际元素个数 int a[100] : 存放数组元素 int max, maxindex : 存放整型数组元素中的最大值及最大值的序号 (2)公有成员函数 ARR(int x[ ], int size): 构造函数,用参数size初始化n,用x数组初始化a数组。 void FindMax( ): 求整型数组元素中的最大值及最大值的序号。 void Show( ): 将数组元素以每行5个数的形式输出到屏幕上,同时输出数组中元素的最大值及最大值的序号。
时间: 2024-01-21 20:16:07 浏览: 46
以下是实现该数组类ARR的C语言代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
typedef struct ARR {
int n; // 数组实际元素个数
int a[MAX_SIZE]; // 存放数组元素
int max; // 存放整型数组元素中的最大值
int maxindex; // 存放整型数组元素中最大值的序号
} ARR;
void ARR_init(ARR *arr, int x[], int size) {
arr->n = size;
for (int i = 0; i < size; i++) {
arr->a[i] = x[i];
}
}
void ARR_FindMax(ARR *arr) {
arr->max = arr->a[0];
arr->maxindex = 1;
for (int i = 1; i < arr->n; i++) {
if (arr->a[i] > arr->max) {
arr->max = arr->a[i];
arr->maxindex = i + 1;
}
}
}
void ARR_Show(ARR *arr) {
printf("数组元素为:\n");
for (int i = 0; i < arr->n; i++) {
printf("%d ", arr->a[i]);
if ((i + 1) % 5 == 0) {
printf("\n");
}
}
printf("\n最大值为:%d,最大值在数组中的序号为:%d\n", arr->max, arr->maxindex);
}
int main() {
int x[MAX_SIZE], size;
printf("请输入数组大小(小于等于100):");
scanf("%d", &size);
printf("请输入数组元素:");
for (int i = 0; i < size; i++) {
scanf("%d", &x[i]);
}
ARR arr;
ARR_init(&arr, x, size);
ARR_FindMax(&arr);
ARR_Show(&arr);
return 0;
}
```
使用时,先输入数组大小和数组元素,然后调用ARR_init函数初始化数组,再调用ARR_FindMax函数求最大值及最大值的序号,最后调用ARR_Show函数输出数组元素和最大值及最大值的序号。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)