C ++中数字流的平均值

平均数是数字的总和除以数字的总数。

在这个问题上,我们得到了一系列的数字。我们将在每个点上打印该数字的平均值。

让我们以它如何工作为例-

我们有5个流24、76、29、63、88

流中每个点的平均值为-

24 , 50 , 43 , 48 , 56.

为此,我们将在每次向流中添加数字时找到流的平均值。因此,我们需要找到1数字,2个数字,3个数字的平均值。我们将利用以前的平均值。

算法

Step 1 : for i -> 0 to n (length of stream).
Step 2 : find the average of elements using formula :
   Average = (average * i) + i / (i+1)
Step 3 : print average.

示例

#include <iostream>
using namespace std;
int main(){
   int arr[] = { 24 , 76 , 29, 63 , 88 };
   int average = 0;
   int n = sizeof(arr) / sizeof(arr[0]);
   for(int i = 0 ; i< n ; i++){
      average = ((average * i) + arr[i]) / (i+1);
      cout<<"The average of "<<i+1<<" numbers of the stream is "<<average<<endl;
   }
   return 0;
}

输出结果

The average of 1 numbers of the stream is 24
The average of 2 numbers of the stream is 50
The average of 3 numbers of the stream is 43
The average of 4 numbers of the stream is 48
The average of 5 numbers of the stream is 56

相同的算法适用于所有数据类型。并可用于计算每个点的平均流量。