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".
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;
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;
Step 3: Use the " " operator to add the N numbers entered by the user
num1 + num2 + ... +numN
Step 4: Use the "/" operator Divide the summation result by N to obtain the average number
将求和结果 / N
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));
【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!