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
對於所有資料型別都可應用相同的演算法。並且可以用來計算每個點的流的平均值。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP