在 JavaScript 中使用 for 循环编写代码,提示用户输入任意数量的数字,打印这些数字中最大和最小的数字

using a for loop in javascript write a code that prompts the user to enter any amount of numbers the print the largest and smallest of those numbers

本文关键字:数字 打印 任意数 用户 for JavaScript 循环 提示 代码 输入      更新时间:2023-09-26

JS的新内容,这是问题所在,代码要求用户输入任意数量的数字-1结束,查找并显示最大和最小的显示;它正在工作,除了它显示最小为最大但最大的显示好??

    var numInputs = parseInt(prompt("Please enter numbers seperated by
      a space end with -1"))
    var largestNum =0;
    var smallestNum = 9999;

if (numInputs >0)
{
  for (i=1; i<=numInputs; i++)
  {
if (numInputs > largestNum)
{
   largestNum = numInputs;
}
  }
}
alert("The largest number entered was " + largestNum);
if (numInputs >0)
{
  for (i=1; i<=numInputs; i++)
  {
    if (numInputs < smallestNum)
    {
   smallestNum = numInputs;
    }
  }
}
alert("The smallest number entered was " + smallestNum);
在这里重构

一下代码怎么样?我们删除parseInt,因为它确实有效,并且通过一个空格将输入的数字split它们,从中制作一个数组sorting the array,然后只需从中popingshifting数字,然后分别删除最后一个和第一个数字。

下面是一个示例。

法典:

var numbers = prompt("please enter a range of numbers separated by a space:");
var arrayOfNumbers = numbers.split(" ").sort();
alert("Lowest entered number:" + arrayOfNumbers.pop() + "'n highest entered number: " + arrayOfNumbers.shift());

代码的问题在于numInputs只解析你输入的第一个数字。 因此,如果输入字符串"1 2 3 4 5 -1",numInputs 将获得值 1。

以下是可以解决您的问题的代码片段:

var largestNum, smallestNum;
var numInput = parseInt(prompt("Please enter the next number (-1 to exit)"));
if (numInput != -1) {
    largestNum = numInput;
    smallestNum = numInput;
}
while (numInput != -1) {
    if (numInput > largestNum) {
        largestNum = numInput;
    } else if (numInput < smallestNum) {
        smallestNum = numInput;
    }
    numInput = parseInt(prompt("Please enter the next number (-1 to exit)"));
}
alert("Smallest number is " + smallestNum + ", largest number is " + largestNum);

如您所见,我会在获得最小和最大数字时实时更新它们,而不是在我获得所有输入之后。此外,为了简单起见,我将第一个数字设置为最小和最大数字(不使用固定值为 0 和 9999,这可能是错误的(。最后,我为每个数字分别做了一个提示,所以你不能把它们一起输入。为此,您必须split字符串并存储在数组中,并迭代数组元素。

你的代码没有太大意义。

numInputs 将是一个字符串(用空格分隔的数字(,你需要在引入数组时解析它,例如:

numInputs = prompt("Please enter numbers...")).split(" ");

然后你应该遍历数组并检查最大和最小数字,例如:

var smallestNum = numInputs[0];
var largestNum = numInputs[0];
for(var i=0; i<numInputs.length; i++) {
    if (smallestNum > numInputs[i]) {
        smallestNum = numInputs[i];
    } else if (largestNum < numInputs[i]) {
        largestNum = numInputs[i];
    }
}
var a = [],
    value;
value = parseInt(prompt("Please enter numbers seperated by a space end with - 1 "));
while (value !== -1) {
    a.push(value);
    value = parseInt(prompt("Please enter numbers seperated by a space end with - 1 "));
}
a.sort();
console.log(a);
alert("The largest number entered was " + a[a.length-1]);
alert("The smallest number entered was " + a[0]);

编辑:如果要对大于 9 的数字进行排序,请使用 :

a.sort(function(a,b){ return a - b });