溫馨提示×

C語言如何找出數組最大值

小億
218
2024-04-11 17:36:03
欄目: 編程語言

可以通過以下方法找出數組中的最大值:

  1. 使用循環遍歷數組,依次比較每個元素與當前最大值,更新最大值。

示例代碼如下:

#include <stdio.h>

int findMax(int arr[], int size) {
    int max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

int main() {
    int arr[] = {3, 5, 1, 8, 2};
    int size = sizeof(arr) / sizeof(arr[0]);
    int max = findMax(arr, size);
    printf("The maximum value in the array is: %d\n", max);
    return 0;
}

這段代碼中,通過定義一個函數findMax來查找數組中的最大值,然后在main函數中調用該函數并輸出最大值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女