用c语言求长度为10的一维数组最大值及其下标
时间: 2024-05-12 08:15:36 浏览: 23
下面是一个用C语言实现的求一维数组最大值及其下标的示例代码:
```c
#include <stdio.h>
#define SIZE 10
int main() {
int arr[SIZE] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
int max = arr[0];
int max_index = 0;
for (int i = 1; i < SIZE; i++) {
if (arr[i] > max) {
max = arr[i];
max_index = i;
}
}
printf("The maximum value is %d at index %d\n", max, max_index);
return 0;
}
```
上面代码中,我们声明了一个长度为10的一维整型数组`arr`,并且初始化了它。然后,我们分别声明了变量`max`和`max_index`,用来保存最大值和最大值所在的下标。接着,我们使用一个`for`循环遍历数组,找到最大值和最大值所在的下标。最后,我们输出最大值和最大值所在的下标。
注意:如果数组中有多个相同的最大值,上面的代码只会输出其中一个最大值所在的下标。如果你想输出所有最大值的下标,可以稍微修改一下代码。
相关问题
用c语言求长度为10的一维数组元素最大值及其下标
可以按照以下步骤实现:
1. 声明一个长度为10的一维整型数组和两个整型变量,用于存储最大值和最大值下标。
2. 通过循环遍历数组中的所有元素,依次与当前最大值进行比较,如果大于当前最大值,则更新最大值和最大值下标。
3. 循环结束后,输出最大值和最大值下标。
下面是示例代码:
```c
#include <stdio.h>
int main() {
int arr[10] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 0}; // 声明长度为10的一维整型数组
int max = arr[0]; // 初始最大值为数组第一个元素
int maxIndex = 0; // 初始最大值下标为0
for (int i = 1; i < 10; i++) { // 循环遍历数组
if (arr[i] > max) { // 如果当前元素大于最大值
max = arr[i]; // 更新最大值
maxIndex = i; // 更新最大值下标
}
}
printf("最大值为:%d,下标为:%d\n", max, maxIndex); // 输出结果
return 0;
}
```
输出结果为:
```
最大值为:9,下标为:4
```
用C语言求长度为10的一维数组元素最大值及其下标
可以使用以下代码实现:
```c
#include <stdio.h>
int main() {
int array[10] = {3, 5, 1, 7, 4, 2, 8, 6, 10, 9}; // 定义长度为10的一维数组
int max = array[0]; // 假设第一个元素为最大值
int index = 0; // 最大值下标初始化为0
for (int i = 1; i < 10; i++) { // 遍历数组
if (array[i] > max) { // 如果当前值大于最大值
max = array[i]; // 更新最大值
index = i; // 更新最大值下标
}
}
printf("最大值为:%d,下标为:%d\n", max, index); // 输出结果
return 0;
}
```
这里假设数组中的元素为 {3, 5, 1, 7, 4, 2, 8, 6, 10, 9},输出结果为:
```
最大值为:10,下标为:8
```
相关推荐
![](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)