C语言程序找出数组列表中两个最大的数字的平均值


2022年2月18日, Learn eTutorial
1585

如何找到最大的两个数字并计算它们的平均值?

在这个C语言程序中,我们需要根据输入的4位数字来计算出最大的两个数字。找到两个最大的数字后,我们需要计算这两个最大数字的总和。最后,将总和除以二,得到两个数字的平均值。

C语言中查找最大值和平均值的逻辑实现

此C语言程序所使用的逻辑是将元素放入数组中,然后将'L1'赋值为数组的第一个元素,将'L2'赋值为数组的第二个元素。使用'if '条件比较'L1'和'L2',如果'L2'大于'L1',则使用temp变量交换'L1'和'L2'的值。

将'L1'与第三个元素进行比较;如果第三个元素大于'L1',则将'L1'更改为'L2',并将第三个元素设置为'L1'。如果第三个元素大于'L2',则将第三个元素设置为'L2'。循环结束后,'L1'和'L2'将是数组中最大和第二大的元素。我们对数组进行排序,然后计算'L1'和'L2'的总和,并除以2来找到平均值。

算法

步骤1:将必要的头文件导入C语言程序中,以便使用内置函数。

步骤2:在程序中初始化并定义数组和其他变量。

步骤3:使用scanffor loop接受用户输入的数字并将其添加到数组中。

步骤4:使用for loopprintf显示数组。

步骤5:假设并将数组的前两个元素分别赋值给L1L2

步骤6:使用'if'条件检查L1是否大于L2

步骤7:如果不是,则使用Temp变量交换L1L2的值。

步骤8:打开一个从2到最大值递增的for loop,并检查最大元素。

步骤9:检查数组的第三个元素是否大于L1,然后将L2赋值给L1,并将数组的第三个元素赋值给L1

步骤10:否则,如果数组的第三个元素大于L2,则将数组的第三个元素赋值给L2

步骤11:最后,在for loop迭代完成后,L1L2将分别包含最大和第二大的元素,然后将L1L2相加,再除以2即可得到平均值。

步骤12:使用C语言的printf打印平均值。

C 语言源代码

                                          #include <stdio>
#include <conio>
#define MAX 4

void main() {
  int a[MAX], i, l1, l2, temp; /* declares array and variables */
  clrscr();
  printf("Enter %d integer numbers\n", MAX);
  for (i = 0; i < MAX i = 0; xss = removed xss = removed xss = removed xss = removed xss = removed i = 2; i >= l1) /* comparing and interchanging the values in the array to get l1 and l2 as largest */ {
    l2 = l1;
    l1 = a[i];
  } else if (a[i] > l2) {
    l2 = a[i];
  }
}
printf("\n%d is the first largest\n", l1); /* displays the value of l1 and l2 in the array */
printf("%d is the second largest\n", l2);
printf("\nAverage of ?nd %d = %d\n", l1, l2, (l1 + l2) / 2); /* calculate and display the average of the two numbers  */
}
                                      

输出

RUN 1

Enter 4 integer numbers
45
33
21
10

Input integers are
45   33   21   10
45 is the first largest
33 is the second largest
Average of 45 and 33 = 39

RUN 2

Enter 4 integer numbers
12
90
54
67

Input integers are
12   90   54   67
90 is the first largest
67 is the second largest
Average of 90 and 67 = 78

RUN 3

Enter 4 integer numbers
100
200
300
400

Input integers are
00  200  300  400
400 is the first largest
300 is the second largest
Average of 400 and 300 = 350