输入2位数时程序不能正常工作


const ps = require("prompt-sync");
const prompt = ps();
console.log("nFinding The Maximum Number In The Array");
console.log("---------------------------------------");
let length = prompt("Enter the length of the array: ");
let temp = 0;
let maxnum;
let array = [];
for(let i=0; i<length;i++){
let num = prompt(i+":");
array[i] = num;
}
console.log("nlength: " + length);
for(let o=0; o < length ; o++ ){
if(array[o] > temp){
temp = array[o];
}
if(o == (length-1)){
maxnum = temp;
console.log("ncurrent max " + maxnum);
}
}
console.log("The maximum number is: "+ maxnum);

在比较1位数时正常工作;比如1 2 3 7。它的输出是7的最大值。但是当向列表中添加10时,程序仍然会输出7.

prompt获得字符串值,当您将字符串值107进行比较时,7被认为是更大的,因为字符串比较是从左到右逐个字符进行的。

首先使用array[i] = parseInt(num);将这些字符串值转换为实际的整数值。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

因为prompt给您一个字符串,所以它按字母顺序比较值。就像字符"C"可以被认为大于字符"A",文本字符"7"也大于文本字符"1"所以就像单词"apple"一样;将按字母顺序排在"CAT"之前,尽管"APPLE"较长,文本字符串"10"在文本字符串"7"之前按字母顺序排序。事实上,文本"1000000"也会出现在文字"7">

要解决这个问题,必须首先将文本字符串转换为数字,这可以通过parseInt()实现。执行此操作的一个方便的地方是在从用户检索字符串输入之后立即执行,如array[i] = parseInt(num);

在提示符处接受输入时,必须将值作为整数存储在数组中。否则默认情况下,这些值将被视为字符串类型。

您可以使用parseInt(yourInput);

最新更新