嗨,我是一个非常新的JavaScript和坚持做我的功课。我的问题是如何在do while循环中一起添加多个输入?我应该将所有输入加在一起,然后除以输入量以获得平均值。例如,如果用户输入7,3,5和2,那么答案将是4.25。这是我到目前为止所做的。
var prompt;
var input = prompt("Please enter a number, input a negative number to stop");
var number = input >= 0;
var alert;
var sum = 0;
var sum2 = 0;
while (input <= 0) {
input = +prompt("Error enter a positive number to start");
}
do {
input = +prompt("Enter another number, a negative to stop");
sum += number;
//inputs added together goes here
} while (input >= 0);
alert(); //inputs added together divided by sum goes here
答案 0 :(得分:0)
增加sum2的值以计算无输入。并添加一个条件,如果用户输入负值,则总数将除以输入数。
我已经编辑了你的代码。
var prompt;
var input = prompt("Please enter a number, input a negative number to stop");
var number;
var alert;
var sum = 0;
var sum2 = 0;
while (input <= 0) {
input = +prompt("Error enter a positive number to start");
}
do {
input = +prompt("Enter another number, a negative to stop");
number=input;
alert(number);
sum += number;
sum2++;
if(input<0){
sum +=(-number);
alert("average"+(sum/(sum2-1)));
}
//inputs added together goes here
} while (input >= 0);
alert();
希望它会有所帮助。
答案 1 :(得分:0)
嗨试试这个版本;
var num = 0, sum = 0, count = 0;
do {
num = parseInt(prompt('Enter Number'));
sum = num >= 0 ? sum+=num : sum;
count = num >= 0 ? count+=1: count; }
while(num >= 0);
console.log(sum + ' count is ' + count);
console.log(sum/count);
基本上我从提示中读取,将输入转换为整数,如果数字为0或更大,我将数字相加。如果数字为0或更大,我将1加到计数中,然后我将总和除以计数
答案 2 :(得分:0)
'use strict';
let input, sum = [];
do {
input = prompt("Enter another number, a negative to stop");
sum.push(input);
} while (input >= 0);
alert(sum.filter((a, b) => {return a + b}) / sum.length);