写一个函数求出n个整数中的最大值及其所在位置,主函数通过键盘输入10个整数,然后通过函数调用求10个整数中的最大值及其所在位置并输出
时间: 2024-03-21 15:39:00 浏览: 22
好的,以下是实现该功能的 C++ 代码:
```cpp
#include <iostream>
using namespace std;
void findMax(int arr[], int n, int& maxVal, int& maxPos) {
maxVal = arr[0];
maxPos = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
maxPos = i;
}
}
}
int main() {
const int n = 10;
int arr[n];
for (int i = 0; i < n; i++) {
cout << "请输入第" << i+1 << "个整数:";
cin >> arr[i];
}
int maxVal, maxPos;
findMax(arr, n, maxVal, maxPos);
cout << "最大值为:" << maxVal << endl;
cout << "所在位置为:" << maxPos << endl;
return 0;
}
```
解释一下,`findMax` 函数接收一个整数数组 `arr`、数组长度 `n`,以及两个引用参数 `maxVal` 和 `maxPos`。函数遍历数组,找到最大值及其所在位置,将它们分别赋值给 `maxVal` 和 `maxPos`。主函数中先从键盘输入 10 个整数,然后调用 `findMax` 函数求出最大值及其所在位置,最后输出结果。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)