Home > Web Front-end > JS Tutorial > body text

How to find the average of multiple numbers in JavaScript

青灯夜游
Release: 2022-02-16 12:55:44
Original
5215 people have browsed it

Method: 1. Store the number to be averaged into an array; 2. Use the "for(i=0;i

How to find the average of multiple numbers in JavaScript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

If you want to find the average of multiple numbers, you need to add the multiple numbers to find the sum, and then divide the sum by the number. So how do you find the average value when you don’t know the specific number of values?

In JavaScript, we can use an array to traverse the array, sum it, and then divide it by the length of the array.

Implementation code:

//数组求元素之和
function getSum(arr) {
	var sum=0,ave=0,i=0;
	for(i=0;i<arr.length;i++) {
	   sum+=arr[i];
	} 
	return sum;
}
//求平均分 
function getAve(arr) {
	var sum=0,ave=0,i=0;
	for(i=0;i<arr.length;i++) {
	   sum+=arr[i];
	} 
	ave=sum/arr.length;
	return ave;
}
//计算结果
var arr=[1,2,3,4,5];
var j=arr.length;
console.log(&#39;这&#39;+j+&#39;个数字为&#39;+arr+&#39;\n&#39;+&#39;这些数字的和为&#39;+getSum(arr)+&#39;\n&#39;+&#39;这些数字的平均值为&#39;+getAve(arr));
Copy after login

How to find the average of multiple numbers in JavaScript

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to find the average of multiple numbers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template