Home > Web Front-end > Front-end Q&A > How to input N data and find the average using JavaScript

How to input N data and find the average using JavaScript

青灯夜游
Release: 2022-10-13 18:20:18
Original
2553 people have browsed it

Implementation steps: 1. Define N variables to store the numbers entered by the user, with the syntax "var n1, n2,..nN;"; 2. Use the prompt() function to obtain the numbers entered by the user and Assign values ​​to N variables, the syntax is "prompt('Please enter data')*1"; 3. Use the " " operator to add and sum the N numbers entered by the user, the syntax is "n1 n2 ... nN"; 4 , use the "/" operator to divide the summation result by N to obtain the average, and the syntax is "divide the summation result/N".

How to input N data and find the average using JavaScript

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

In javascript, you can use the prompt() function, " " and "/" operators to input N data and find the average

Implementation steps:

Step 1: Define N variables to store the numbers entered by the user

var num1,num2,..numN;
Copy after login

Step 2: Use the prompt() function Obtain the number entered by the user and assign it to two variables. The

prompt() method is used to display a dialog box that prompts the user for input. The function return value is a string.

When the user input is a number or Boolean type, string type will always be returned. If you want to keep the type unchanged, you need to perform type conversion.

num1 = prompt('请输入第一个数字') * 1;
num2 = prompt('请输入第二个数字') * 1;
...
numN = prompt('请输入第N个数字') * 1;
Copy after login

Step 3: Use the " " operator to add the N numbers entered by the user

num1 + num2 + ... +numN
Copy after login

Step 4: Use the "/" operator Divide the summation result by N to obtain the average number

将求和结果 / N
Copy after login

Implementation code: The user inputs 3 data to find the average

var num1 = prompt('请输入第一个数字') * 1;
var num2 = prompt('请输入第二个数字') * 1;
var num3 = prompt('请输入第三个数字') * 1;
var sum = num1 + num2 + num3;
console.log("用户输入3个数据的平均数:"+(sum/3));
Copy after login

How to input N data and find the average using JavaScript

【Related recommendations: javascript video tutorial, programming video

The above is the detailed content of How to input N data and find the average using 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