Average Calculation not Working!

Enthusiast ,
Dec 12, 2021 Dec 12, 2021

Copy link to clipboard

Copied

Hi Experts,

I wrote simple Average calculations but it not working, also no errors! please help me to know what i did wrong! and Thanks in Advance.

var MyNumbers = [5,5,6,7];
var FinalSum = 0;
var ArrAverage = 0;

function DoAverage() { // average values in array;

for(var i = 0; i < MyNumbers.length; i++) {
    FinalSum +=Number(MyNumbers[i]);
    }

if(MyNumbers.length > 0) {
    ArrAverage = FinalSum / MyNumbers.length;
    }

return DoAverage;
    alert("Average is " + Number(ArrAverage));
} // end DoAverage function;

DoAverage();

 

Best
M.Hasanain
TOPICS
Scripting

Views

95

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 2 Correct answers

Community Expert , Dec 12, 2021 Dec 12, 2021

Hi @M.Hasanain, remove the line "return DoAverage;"

- Mark

Likes

Translate

Translate
Community Expert , Dec 12, 2021 Dec 12, 2021

For learning, please compare it to this version:

 

 

var MyNumbers = [5, 5, 6, 7];

alert('Average is ' + getAverage(MyNumbers));


function getAverage(numbersArray) {
    var sum = 0;
    for (var i = 0; i < numbersArray.length; i++) {
        sum += numbersArray[i];
    }
    
    var average = 0;
    if (sum > 0) {
        average = sum / numbersArray.length;
    }

    return average;
}

 

 

Likes

Translate

Translate
Community Expert ,
Dec 12, 2021 Dec 12, 2021

Copy link to clipboard

Copied

Hi @M.Hasanain, remove the line "return DoAverage;"

- Mark

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Enthusiast ,
Dec 12, 2021 Dec 12, 2021

Copy link to clipboard

Copied

LATEST

Thanks a lot @m1b , i forget to remove this line !

Best
M.Hasanain

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Dec 12, 2021 Dec 12, 2021

Copy link to clipboard

Copied

For learning, please compare it to this version:

 

 

var MyNumbers = [5, 5, 6, 7];

alert('Average is ' + getAverage(MyNumbers));


function getAverage(numbersArray) {
    var sum = 0;
    for (var i = 0; i < numbersArray.length; i++) {
        sum += numbersArray[i];
    }
    
    var average = 0;
    if (sum > 0) {
        average = sum / numbersArray.length;
    }

    return average;
}

 

 

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines