在这个 C 语言程序中,我们需要计算给定数字列表或数组中的第二大和第二小的数字。同时,计算第二大和第二小数字的平均值。然后再次检查平均值是否存在于列表中。
要找出数组中的第二大数字,我们必须将数组按降序排序。这意味着将数字从大到小排列。因此,数组中第二个位置的数字将是第二大数字。在排序数组之后,这很容易得到。
要查找数组中的第二小数字,我们必须将数组按降序排序,这意味着将数字从大到小排列。因此,数组中第 n-2 个位置的数字将是第二小数字。
此程序的逻辑是,首先从用户读取一些数字并将其保存在一个数组中。通过使用嵌套的 for 循环,将数字按降序排列。然后显示按降序排列的数字作为排序后的数组。将第二大数字显示为 number[1],将第二小数字显示为 number[n-2]。
现在计算 average = (number[1] + number[n-2]) / 2。将 counter = 0。通过使用带有条件“ i ”的 for 循环
步骤1: 包含头文件,以便在C程序中使用内置函数。
步骤 2: 声明整数变量 i, j, a, n, counter, ave 和数组 number[30]。
步骤 3:将 N 的值读取到变量 n 中。
步骤 4: 使用 for 循环将数字读取到数组 number[i] 中。
步骤 5: 设置 i=0。
步骤 6: 检查条件 i
步骤 7: 设置 j=i+1。
步骤 8: 检查是否 number[i]
步骤 9: 将 j 增加 1 并执行步骤 8。
步骤 10: 将 'i' 增加 1 并执行步骤 6。
步骤 11: 使用 for 循环显示按降序排列的数字作为数组 number[] 中的数字。
步骤 12: 显示第二大数字为 number[1]。
步骤 13: 显示第二小数字为 number[n-2]。
步骤 14: 计算 ave=(number[1] +number[n-2])/2。
步骤 15: 设置 counter=0。
步骤 16: 通过使用带有条件 i 的 for 循环
步骤 17: 检查是否 ave==number[i],然后将 counter 增加 1。
步骤 18: 通过将 'i' 的值增加 1 来重复步骤 16。
步骤 19: 检查是否 counter==0,然后显示 number[1] 和 number[n-2] 的平均值 = ave 不在数组中。
步骤 20: 检查是否 counter==1,然后显示 number[1] 和 number[n-2] 的平均值 = ave 存在于数组中。
#include <stdio.h>
void main() {
int number[30];
int i, j, a, n, counter, ave;
printf("Enter the value of N\n");
scanf("%d", & n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", & number[i]);
for (i = 0; i < n; ++i) {
for (j = i + 1; j < n; ++j) {
if (number[i] < number[j]) {
a = number[i]; /* interchange the numbers to make it in proper order */
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in descending order are given below\n");
for (i = 0; i < n; ++i) {
printf("%d\n", number[i]);
}
printf("The 2nd largest number is = %d\n", number[1]);
printf("The 2nd smallest number is = %d\n", number[n - 2]);
ave = (number[1] + number[n - 2]) / 2;
counter = 0;
for (i = 0; i < n; ++i) {
if (ave == number[i]) {
++counter;
}
}
if (counter == 0)
printf("The average of %d and %d is = %d is not in the array\n", number[1], number[n - 2], ave);
else
printf("The average of ?nd %d in array is %d in numbers\n", number[1], number[n - 2], counter);
} /* End of main() */
Enter the value of N 6 Enter the numbers 30 80 10 40 70 90 The numbers arranged in descending order are given below 90 80 70 40 30 10 The 2nd largest number is = 80 The 2nd smallest number is = 30 The average of 80 and 30 is = 55 is not in the array