用c++语言在一个10个整数的数组中找出最小数和其下标,并在主函数中打印最小数和下标。
时间: 2024-10-12 14:09:28 浏览: 91
在C++中,你可以通过遍历整个数组来找到最小值及其索引。这里是一个简单的示例程序:
```cpp
#include <iostream>
using namespace std;
// 函数声明,用于返回最小元素的下标
int findMinIndex(int arr[], int size);
int main() {
int arr[10] = {5, 9, 1, 7, 3, 8, 6, 2, 4, 0}; // 初始化一个包含10个整数的数组
int minVal = arr[findMinIndex(arr, 10)]; // 调用函数获取最小值
int minIndex = findMinIndex(arr, 10); // 同样获取最小值的下标
cout << "The minimum number is: " << minVal << endl;
cout << "Its index in the array is: " << minIndex << endl;
return 0;
}
// 实现寻找最小值下标的辅助函数
int findMinIndex(int arr[], int size) {
int minIndex = 0; // 假设第一个元素是最小的
for (int i = 1; i < size; i++) { // 从第二个元素开始比较
if (arr[i] < arr[minIndex]) {
minIndex = i; // 更新最小值的下标
}
}
return minIndex;
}
```
这个程序首先初始化了一个包含10个整数的数组,然后调用`findMinIndex`函数找出数组中的最小值及其下标,并将结果打印出来。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.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)