How to find the largest and smallest values when inputting n numbers in the C language?

To find the maximum and minimum values of n numbers, you can achieve this by following these steps:

  1. First, declare two variables, max and min, to store the maximum and minimum values respectively. Set the initial values of max and min to be the first input number.
  2. Input n numbers in a loop, each time inputting a number, compare the number with the current maximum and minimum values, and update the values of max and min.
  3. After the loop ends, max and min respectively hold the maximum and minimum values among n numbers.

Here is an example code:

#include <stdio.h>

int main() {
    int n, num, max, min;
    
    // 输入n的值
    printf("请输入数的个数n:");
    scanf("%d", &n);
    
    // 输入第一个数
    printf("请输入第1个数:");
    scanf("%d", &num);
    
    // 初始化最大值和最小值
    max = num;
    min = num;
    
    // 输入剩余的n-1个数,比较更新最大值和最小值
    for (int i = 2; i <= n; i++) {
        printf("请输入第%d个数:", i);
        scanf("%d", &num);
        
        if (num > max) {
            max = num;
        }
        
        if (num < min) {
            min = num;
        }
    }
    
    // 输出结果
    printf("最大值:%d\n", max);
    printf("最小值:%d\n", min);
    
    return 0;
}

In this example, the first step is to enter the value of n, followed by entering n numbers. The program will automatically calculate the maximum and minimum values of these n numbers and output the results.

bannerAds