C语言代码,找出一个数组中的最大值及其下标
时间: 2024-05-15 15:18:59 浏览: 8
好的,关于你的问题,我可以回答。以下是一个 C 语言代码,可以找出一个数组中的最大值及其下标:
```c
#include <stdio.h>
#define MAX_SIZE 100
int main() {
int arr[MAX_SIZE], n, max, index;
printf("请输入数组的元素个数:");
scanf("%d", &n);
printf("请输入数组的%d个元素:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
max = arr[0];
index = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
index = i;
}
}
printf("数组中最大值为%d,下标为%d\n", max, index);
return 0;
}
```
希望能帮到你!
相关问题
请用C语言编写函数,找出一维数组最大值并返回下标
当然可以!下面是使用C语言编写的函数来找出一维数组的最大值并返回其下标的示例代码:
```c
#include <stdio.h>
int findMaxIndex(int arr[], int size) {
int maxIndex = 0; // 假设初始最大值下标为0
for (int i = 1; i < size; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i; // 更新最大值下标
}
}
return maxIndex;
}
int main() {
int arr[] = {5, 2, 9, 1, 7}; // 示例数组
int size = sizeof(arr) / sizeof(arr[0]); // 数组大小
int maxIndex = findMaxIndex(arr, size);
printf("最大值为:%d,下标为:%d\n", arr[maxIndex], maxIndex);
return 0;
}
```
在这个示例代码中,我们定义了一个 `findMaxIndex` 函数,该函数接受一个整数数组和数组大小作为参数。它通过遍历数组来查找最大值,并将最大值的下标存储在 `maxIndex` 变量中。然后,在 `main` 函数中调用 `findMaxIndex` 函数,并打印出最大值和其对应的下标。
运行以上代码,将输出:
```
最大值为:9,下标为:2
```
这表示数组中最大的元素是9,它的下标是2。
C语言求数组中最大值和下标
好的,下面是C语言的代码实现,同样假设您的数组为arr,长度为n:
```c
int max_val = arr[0];
int max_index = 0;
for(int i = 1; i < n; i++){
if(arr[i] > max_val){
max_val = arr[i];
max_index = i;
}
}
printf("最大值为:%d\n", max_val);
printf("最大值下标为:%d\n", max_index);
```
以上代码同样会遍历整个数组,逐个比较找出最大值和对应下标。