給定數對 (w₁, v₁), (w₂, v₂), ..., (wₙ, vₙ),加權平均數為:
Weighted Average = (Σ wᵢ × vᵢ) / (Σ wᵢ)
#include
#include
using namespace std;
int main() {
double weight, value;
double sumWV = 0.0, sumW = 0.0;
cout << "請輸入權重和數值(以空格分隔,Ctrl+Z 結束):\n";
while (cin >> weight >> value) {
sumWV += weight * value;
sumW += weight;
}
if (sumW != 0) {
double weightedAvg = sumWV / sumW;
cout << fixed << setprecision(4);
cout << "加權平均數 = " << weightedAvg << endl;
} else {
cout << "無有效輸入或權重總和為零。" << endl;
}
return 0;
}
輸入: 0.2 80 0.3 90 0.5 70 ^Z 計算: (0.2×80 + 0.3×90 + 0.5×70) / (0.2+0.3+0.5) = (16 + 27 + 35) / 1.0 = 78.0
while(!cin.eof()) 導致多讀一次)。若權重總和 = 1,加權平均即為**期望值 E[X]**。