Program for weighted mean of natural numbers . | Program to find weighted mean of natural numbers . ; Function to calculate weighted mean . ; Driver program to test the function . ; Take num array and corresponding weight array and initialize it . ; Calculate the size of array . ; Check the size of both array is equal or not .
#include <bits/stdc++.h> NEW_LINE using namespace std ; float weightedMean ( int X [ ] , int W [ ] , int n ) { int sum = 0 , numWeight = 0 ; for ( int i = 0 ; i < n ; i ++ ) { numWeight = numWeight + X [ i ] * W [ i ] ; sum = sum + W [ i ] ; } return ( float ) numWeight / sum ; } int main ( ) { int X [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; int W [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; int n = sizeof ( X ) / sizeof ( X [ 0 ] ) ; int m = sizeof ( W ) / sizeof ( W [ 0 ] ) ; if ( n == m ) cout << weightedMean ( X , W , n ) ; else cout << " - 1" ; return 0 ; }