用:int* findmin(int *minIndex, int a[], int size=10); double* findmin(int *minIndex, double a[], int size=10);函数原型编写出一个findmin函数,能寻找数组中的最小元素
时间: 2023-12-11 16:06:01 浏览: 61
数组中求最小元素——C++代码
可以使用函数重载,根据传入的数组类型调用对应的函数,来编写一个能寻找数组中最小元素的`findmin`函数,代码如下:
```cpp
#include <iostream>
using namespace std;
int* findmin(int *minIndex, int a[], int size=10);
double* findmin(int *minIndex, double a[], int size=10);
int main() {
int arr1[] = {5, 3, 8, 1, 9, 2};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int minIndex1;
int* ptr1 = findmin(&minIndex1, arr1, n1);
cout << "The minimum value in the integer array is: " << *ptr1 << ", and its index is: " << minIndex1 << endl;
double arr2[] = {5.1, 3.2, 8.5, 1.2, 9.7, 2.4};
int n2 = sizeof(arr2) / sizeof(arr2[0]);
int minIndex2;
double* ptr2 = findmin(&minIndex2, arr2, n2);
cout << "The minimum value in the double array is: " << *ptr2 << ", and its index is: " << minIndex2 << endl;
return 0;
}
int* findmin(int *minIndex, int a[], int size) {
int min_val = a[0];
*minIndex = 0;
for (int i = 1; i < size; i++) {
if (a[i] < min_val) {
min_val = a[i];
*minIndex = i;
}
}
return &a[*minIndex];
}
double* findmin(int *minIndex, double a[], int size) {
double min_val = a[0];
*minIndex = 0;
for (int i = 1; i < size; i++) {
if (a[i] < min_val) {
min_val = a[i];
*minIndex = i;
}
}
return &a[*minIndex];
}
```
运行结果为:
```
The minimum value in the integer array is: 1, and its index is: 3
The minimum value in the double array is: 1.2, and its index is: 3
```
注意,这里为了方便输出最小元素的索引,将 `minIndex` 定义为指针类型,传入函数时需要使用 `&` 取地址符号。函数内部通过修改 `minIndex` 指向的地址来返回最小元素的索引。
阅读全文