给定一个自然数数组和一个包含相应自然数权重的数组,任务是计算自然数的加权平均值。
有一个公式可用于计算自然数的加权平均值。
$$\ overline {x} = \ frac {\ displaystyle \ sum \ limits_ {i = 1} ^ n(x_ {i *} w_ {i})} {\ displaystyle \ sum \ limits_ {i = 1} ^ n w_ {i}} $$
其中,x是自然数,w是与该自然数相关联的权重。
输入项
X[] = {11, 22, 43, 34, 25, 16} W[] = {12, 12, 43, 54, 75, 16}
输出结果
weighted mean is : 29.3019
说明
(11*12 + 22*12 + 43*43 + 34*54 + 25*75 + 16*16) / (12 + 12 + 43 + 54 +75 +16)
输入项
X[] = {3, 4, 5, 6, 7} W[] = {4, 5, 6, 7, 8}
输出结果
weighted mean is : 5.33333
说明
(3*4 + 4*5 + 5*6 + 6*7 + 7*8) / (4 + 5 + 6 + 7 + 8)
输入两个不同的数组,一个用于自然数,另一个用于相应自然数的权重。
应用公式计算自然数的加权平均值
打印相应的结果。
Start Step1→ declare function to calculate weighted means of natural numbers float weightedmean(int X[], int W[], int size) Declare int sum = 0, weight = 0 Loop For int i = 0 and i < size and i++ Set weight = weight + X[i] * W[i] Set sum = sum + W[i] End return (float)weight / sum Step 2→ In main() Declare int X[] = {11, 22, 43, 34, 25, 16} Declare int W[] = {12, 12, 43, 54, 75, 16} Declare int size_X = sizeof(X)/sizeof(X[0]) Declare int size_W = sizeof(W)/sizeof(W[0]) IF (size_X == size_W) Call weightedmean(X, W, size_X) End Else Print -1 End Stop
#include<bits/stdc++.h> using namespace std; //计算加权平均值。 float weightedmean(int X[], int W[], int size){ int sum = 0, weight = 0; for (int i = 0; i < size; i++){ weight = weight + X[i] * W[i]; sum = sum + W[i]; } return (float)weight / sum; } int main(){ int X[] = {11, 22, 43, 34, 25, 16}; int W[] = {12, 12, 43, 54, 75, 16}; int size_X = sizeof(X)/sizeof(X[0]); int size_W = sizeof(W)/sizeof(W[0]); if (size_X == size_W) cout<<"weighted mean is : "<<weightedmean(X, W, size_X); else cout << "-1"; return 0; }
输出结果
如果运行上面的代码,它将生成以下输出-
weighted mean is : 29.3019