Home > Web Front-end > Front-end Q&A > How to find the average of three numbers in javascript

How to find the average of three numbers in javascript

青灯夜游
Release: 2022-02-07 15:12:16
Original
4082 people have browsed it

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".

How to find the average of three numbers in javascript

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);
Copy after login

How to find the average of three numbers in javascript

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(&#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 three numbers in javascript

【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!

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