使用c++查找数组中最大值返回其下标
时间: 2023-11-18 10:03:49 浏览: 145
可以使用以下代码实现:
```c
#include <stdio.h>
int findMaxIndex(int arr[], int length) {
int maxIndex = 0;
for (int i = 1; i < length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
int main() {
int arr[] = {1, 5, 3, 9, 7};
int length = sizeof(arr) / sizeof(arr[0]);
int maxIndex = findMaxIndex(arr, length);
printf("The index of the maximum value is: %d\n", maxIndex);
return 0;
}
```
在这个程序中,`findMaxIndex` 函数遍历数组并记录最大值的下标,然后返回该下标。在 `main` 函数中,我们调用 `findMaxIndex` 函数并打印最大值的下标。
相关问题
c++写从键盘输入10个整数并保存到数组,,输出10个整数中的最大值以及其下标、最小值及其下标
#include <stdio.h>
int main()
{
int arr[10];
int max = 0, min = 0;
int max_index = 0, min_index = 0;
// 从键盘输入10个整数并保存到数组
printf("请输入10个整数:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
// 查找最大值和最小值以及其下标
for (int i = 0; i < 10; i++) {
if (arr[i] > arr[max_index]) {
max_index = i;
}
if (arr[i] < arr[min_index]) {
min_index = i;
}
}
max = arr[max_index];
min = arr[min_index];
// 输出结果
printf("最大值:%d,下标:%d\n", max, max_index);
printf("最小值:%d,下标:%d\n", min, min_index);
return 0;
}
c++用指针变量设计一通用函数,该函数查找实型数组中最大和最小元素并输出相应元素和下标。
下面是代码实现:
```c++
#include <iostream>
using namespace std;
void findMinMax(double* arr, int size, double& minVal, int& minIndex, double& maxVal, int& maxIndex) {
minVal = arr[0];
minIndex = 0;
maxVal = arr[0];
maxIndex = 0;
for(int i = 1; i < size; i++) {
if(arr[i] < minVal) {
minVal = arr[i];
minIndex = i;
}
if(arr[i] > maxVal) {
maxVal = arr[i];
maxIndex = i;
}
}
}
int main() {
double arr[] = {4.5, 2.1, 6.7, 1.2, 8.9};
int size = sizeof(arr) / sizeof(double);
double minVal, maxVal;
int minIndex, maxIndex;
findMinMax(arr, size, minVal, minIndex, maxVal, maxIndex);
cout << "Min value: " << minVal << ", index: " << minIndex << endl;
cout << "Max value: " << maxVal << ", index: " << maxIndex << endl;
return 0;
}
```
在上面的代码中,我们通过传递指向数组的指针变量来遍历数组元素,同时使用引用变量来返回最小值、最小值索引、最大值和最大值索引。在函数内部,我们使用了 if 语句来更新最小值和最大值,并使用索引变量来跟踪它们的位置。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)