如何在javascript

时间:2016-11-27 16:12:01

标签: javascript

如何添加到此程序中以查找最高和最低数字?我尝试了一些不同的东西,但它只是给我输入我输入的最后一个数字。

<meta charset="UTF-8">
<title>Laskenta</title>
<script>

var yht=0; //sum
var luku=0; //number
var laske; //count

laske=Number(prompt("how many numbers would you like to add?"))
for (var i=0; i<laske; i++){luku = Number(prompt("give number", "number")); 

yht=yht+luku;

} 
while(i<laske);

document.write("the sum of the numbers you entered is " ,yht, "<br>");
document.write (" and the average is o " + yht/laske); 

我将大部分内容翻译成芬兰语,然后将旁边的内容放在芬兰语旁边。 任何帮助将不胜感激。 感谢

2 个答案:

答案 0 :(得分:0)

第一组操作解决了您在循环中执行这些任务所需的操作,但您并不需要传统的循环来执行这些任务。新的spread operator along with Math.maxArray.prototype.reduce()方法可以轻松获得最大值,总和或平均值。

&#13;
&#13;
var result = null;
var nums = [];

// Remember, a propmt will always return a string, you must convert that
// to a number if you want to do math with it.
var count = parseInt(prompt("How many numbers do you want to work with?"), 10);

// Build up the input values into an array:
for(var i = 0; i < count; ++i){
  nums.push(parseInt(prompt("Enter number " + (i + 1)),10));
}

// The "traditional" way to get the max value from a loop would be to
// compare the value that you are iterating and the next value in the
// array and store the higehr one:
var max = null;
var sum = 0;
for(var x = 0; x < nums.length-1; ++x){
     max = (nums[x] > nums[x + 1]) ? nums[x] : nums[x + 1];
     sum += nums[x];
}
console.log("Max number is: " + max);

var sum = 0;
for(var y = 0; y < nums.length; ++y){
     sum += nums[y];
}
console.log("Sum is: " + sum);
console.log("Average is: " + sum / nums.length);
  
// *******************************************************************************
// But, we have much better ways of doing these jobs:
console.log("Max number is: " + Math.max(...nums));

result = nums.reduce(function(accumulator, currentValue, currentIndex, array) {
  return accumulator + currentValue;
});

console.log("The sum is: " + result);
console.log("The average is: " + result / nums.length);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var yht=0; //sum
var luku=0; //number
var laske; //count
var highest;
var lowest;

laske=Number(prompt("how many numbers would you like to add?"))
for (var i=0; i<laske; i++){luku = Number(prompt("give number", "number")); 
if (i == 0) {
highest = luku;
lowest = luku;
}
else {
  if (luku > highest) highest = luku;
  if (luku < lowest) lowest = luku;
}
yht=yht+luku;

} 
while(i<laske);

document.write("the sum of the numbers you entered is " ,yht, "<br>");
document.write (" and the average is o " + yht/laske); 
document.write("<br />Highest value="+highest);
document.write("<br />Lowest value="+lowest);

在代码中添加两个变量以跟踪输入的最高和最低值。将输入的第一个数字设置为最高和最低。然后当遇到新的低点时,替换为最低值。遇到新的高值时,请替换为最高值。

相关问题