编写程序,输出一维数组a中的元素最小值及其下标。
时间: 2024-06-13 22:07:05 浏览: 196
以下是C语言程序设计中输出一维数组a中的元素最小值及其下标的代码:
```c
#include <stdio.h>
int main() {
int a[10] = {9, 8, 7, 6, 1, 3, 5, 18, 2, 4};
int m = a[0], p = 0;
for (int i = 1; i < 10; i++) {
if (a[i] < m) {
m = a[i];
p = i;
}
}
printf("元素最小值为:%d,其下标为:%d\n", a[p], p);
return 0;
}
```
该程序首先定义了一个包含10个元素的一维数组a,并将第一个元素赋值给变量m,将下标0赋值给变量p。然后通过for循环遍历数组中的每一个元素,如果当前元素小于m,则将当前元素赋值给m,将当前下标赋值给p。最后输出最小值和其下标。
相关问题
编写程序,输出一维数组a中的元素最小值及其下标
好的,我可以回答这个问题。以下是一个简单的Python代码实现:
```python
a = [23, 45, 12, 67, 89, 43, 56]
min_val = min(a)
min_index = a.index(min_val)
print("最小值为:", min_val, ",下标为:", min_index)
```
输出结果为:
```
最小值为: 12 ,下标为: 2
```
希望这个回答能够帮到你!
编写一个函数,同时返回一维数组的最小值及其下标。
可以使用以下函数实现:
```python
def min_with_index(arr):
min_val = arr[0]
min_idx = 0
for i in range(1, len(arr)):
if arr[i] < min_val:
min_val = arr[i]
min_idx = i
return min_val, min_idx
```
该函数使用循环遍历数组,并比较每个值以找到最小值及其下标。最后将最小值和下标作为元组返回。您可以通过以下方式调用该函数:
```python
my_arr = [8, 2, 5, 1, 7]
min_val, min_idx = min_with_index(my_arr)
print("The minimum value is", min_val, "at index", min_idx)
```
输出将是:
```
The minimum value is 1 at index 3
```
请注意,如果有多个最小值,则该函数将返回第一个找到的最小值及其下标。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.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://img-home.csdnimg.cn/images/20241231044937.png)