กำหนดด้วยอาร์เรย์ของจำนวนธรรมชาติและอีกหนึ่งอาร์เรย์ที่มีน้ำหนักของจำนวนธรรมชาติที่สอดคล้องกัน และภารกิจคือการคำนวณค่าเฉลี่ยถ่วงน้ำหนักของจำนวนธรรมชาติ
มีสูตรที่ใช้คำนวณค่าเฉลี่ยถ่วงน้ำหนักของจำนวนธรรมชาติ
$$\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;
//calculate weighted mean.
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