编写函数 int Sum(int a[])、int Max(int a])、int Min(int a[])和int Process(int a[],int (*fun)(int])),分别求数组a所有元素之和、最大值、最小值,通过调用 函数 Process 实现调用函数 Sum、Max和Min。
时间: 2024-02-27 22:56:35 浏览: 19
好的,可以的。这四个函数的实现分别如下:
```c++
// 计算数组a中所有元素的和
int Sum(int a[]) {
int sum = 0;
for (int i = 0; i < sizeof(a)/sizeof(a[0]); i++) {
sum += a[i];
}
return sum;
}
// 找出数组a中的最大值
int Max(int a[]) {
int max = a[0];
for (int i = 1; i < sizeof(a)/sizeof(a[0]); i++) {
if (a[i] > max) {
max = a[i];
}
}
return max;
}
// 找出数组a中的最小值
int Min(int a[]) {
int min = a[0];
for (int i = 1; i < sizeof(a)/sizeof(a[0]); i++) {
if (a[i] < min) {
min = a[i];
}
}
return min;
}
// 对数组a进行处理,使用函数fun来处理数组中的每个元素
int Process(int a[], int (*fun)(int)) {
int result = 0;
for (int i = 0; i < sizeof(a)/sizeof(a[0]); i++) {
result += fun(a[i]);
}
return result;
}
```
需要注意的是,在函数Process中,我们传入了一个函数指针`int (*fun)(int)`作为参数,这个指针指向的函数可以是Sum、Max或Min。在函数内部,我们使用`fun(a[i])`来调用传入的函数,对数组中的每个元素进行处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)