Home > Article > Web Front-end > How to find the average of three numbers in javascript
Method: 1. Use the " " operator to add the three numbers and assign them to the variable "sum". The syntax is "sum=value 1 value 2 value 3"; 2. Use "/" The operator adds the sum of three numbers and divides it by 3, and assigns it to the variable "ave". The syntax is "ave=sum/3"; 3. Output the value of the variable "ave".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Javascript implements the average of three numbers
The average refers to the sum of all the data in a set of data divided by the set The number of data.
We only need to add the three numbers and then divide by 3.
For example, there are three numbers: 1, 2, 3, and their average is:
Implementation code:
var a,b,c,sum,ave; a=1; b=2; c=3; sum=a+b+c; ave=sum/3; console.log(ave);
This is If you know the specific number of data, how can you find the average if you don’t know?
We can use arrays.
//数组求元素之和 function getSum(arr) { var sum=0,ave=0,i=0; for(i=0;i<arr.length;i++) { // alert(arr); sum+=arr[i]; } return sum; } //求平均分 function getAve(arr) { var sum=0,ave=0,i=0; for(i=0;i<arr.length;i++) { // alert(arr); sum+=arr[i]; } ave=sum/arr.length; return ave; } //计算结果 var arr=[1,2,3,4,5]; var j=arr.length; // getSum(arr); alert('这'+j+'个数字为'+arr+'\n'+'这些数字的和为'+getSum(arr)+'\n'+'这些数字的平均值为'+getAve(arr));
【Related recommendations: javascript learning tutorial】
The above is the detailed content of How to find the average of three numbers in javascript. For more information, please follow other related articles on the PHP Chinese website!