C 语言程序,用于查找数组中正数和负数的和与平均值


2023 年 1 月 9 日, Learn eTutorial
2987

C 语言中的数组是什么?

数组是相同数据类型元素的集合,存储在连续的内存位置中,可以通过索引变量访问.

数组声明为 数据类型 数组名[大小],例如“int array[23]”。它使用连续的内存位置,因此最低地址(起始地址)也称为 基地址,它包含第一个元素,最高地址包含数组的最后一个元素。

如何使用 C 语言计算正数和负数的平均值和总和?

在这个 C 语言程序中,我们将用户输入添加到数组中,因此我们可以通过将数组索引递增一来访问元素。现在我们使用另一个 for 循环 显示数字。之后,打开另一个 for 循环 来检查每个元素是正数负数还是

  • 如果它是正数,则将其添加到正数和变量中.
  • 如果它是负数,则将其添加到负数和变量中。
  • 否则,它就是

然后我们通过将数字添加到总和来计算总和。最后,我们通过将总和除以元素数量来计算平均值,并单独显示结果。

算法

步骤 1: 将头文件包含到 C 程序中,以使用内置函数。

步骤 2: 声明并初始化变量和数组。

步骤 3: 使用 printfscanf 接受用户所需的项数。

步骤 4: 打开 'for 循环' 接受数字并将其添加到数组中。

步骤 5: 使用另一个 'for 循环' 显示元素。

步骤 6: 打开一个 for 循环,从 '0' 到 '项数',检查每个元素。

步骤 7: 使用 'if' 条件检查数字是否小于零,将其添加到负数和中。

步骤 8: 否则,如果数字大于零,将其添加到正数和中。

步骤 9: 否则,元素为零,无需执行任何操作。

步骤 10: 在 'for 循环' 的每次迭代中,将数组元素与总和相加。

步骤 11: 通过将总和除以元素总数来计算“平均值”。

步骤 12: 使用 C 语言中的 printf 打印正数和、负数和平均值


此程序使用 C 语言编程中的以下概念,我们建议阅读这些主题以获得更好的理解。

C 语言源代码

                                          #include <stdio.h>
#define MAXSIZE 10               /* defines array size 10 */

void main() 
{
   int array[MAXSIZE];
   int i, N, negsum = 0, posum = 0;
   float total = 0.0, averg;
   printf("Enter the value of N\n");
   scanf("%d", & N);
   printf("Enter %d numbers (-ve, +ve and zero)\n", N);            /* enter the user input into the array we defined */
   for (i = 0; i < N; i++) 
   {
      scanf("%d", & array[i]);
      fflush(stdin);
   }
   printf("Input array elements\n");
   for (i = 0; i < N; i++) 
   {
      printf("%+3d\n", array[i]);            /* prints the values inside of the array using 3 positions*/
   }

  /* Summing  begins */

  for (i = 0; i < N; i++) 
  {
      if (array[i] < 0) 
      {
         negsum = negsum + array[i];                 /* if number is negative it gets added to negative sum */
      }
     else if (array[i] > 0) 
     {
        posum = posum + array[i];                      /* if number is positive it gets added to positive sum */
     }
    else if (array[i] == 0) 
    {
        ;
    }
     total = total + array[i];
   }
   averg = total / N;                  /* calculating average */
   printf("\nSum of all negative numbers    = %d\n", negsum);           /* displays the output */
   printf("Sum of all positive numbers    = %d\n", posum);
   printf("\nAverage of all input numbers   = %.2f\n", averg);
} 
                                      

输出

Enter the value of N
5

Enter 5 numbers (-ve, +ve and zero)
5
-3
0
-7
6

Input array elements
+5
-3
+0
-7
+6
Sum of all negative numbers    = -10

Sum of all positive numbers    = 11

Average of all input numbers   = 0.20