I'我试图创建一个函数,将范围(0-100)内的三个数字随机化,并打印最大的一个

I'm trying to create a function that Randomizes three numbers in range (0-100) and prints the largest one

本文关键字:一个 打印 随机化 0-100 数字 三个 函数 创建 范围      更新时间:2023-09-26

。。。但当我在控制台中调用函数时,它返回未定义的结果。我是一个JavaScript新手,所以我可能犯了一个基本错误,如果有人能帮我,我会很高兴的:-)。

这是代码:

var randomPrint = function(){
x = Math.floor(Math.random() * 100);
y = Math.floor(Math.random() * 100);
z = Math.floor(Math.random() * 100);
   console.log(x, y, z);
   if(x > y && x > z)
   {
     console.log("The greatest number is" + " " + x);
   }
   else if(y > z && y > x)
   { 
     console.log("The greatest number is" + " " + y);
   }
   else if(z > y && z > x)
   {   
    console.log("The greatest number is" + " " + z);
   }
};
randomPrint();

理智的方式:

var nums = [];
for (var i = 0; i < 3; i++) {
    nums.push(Math.floor(Math.random() * 100));
}
console.log('Largest number is ' + Math.max.apply(null, nums));

或者:

nums = nums.sort();
console.log('Largest number is ' + nums[nums.length - 1]);

是的,函数将返回undefined,因为您不会从函数返回任何内容。很可能你的条件都不匹配,所以你也看不到任何其他输出。

试试这个内置的方法来获得最大

Math.max(x,y,z);

如果你能扔掉另外两个数字:

for (var i = 0, max = -Infinity; i < 3; ++i) {
    max = Math.max(Math.floor(Math.random() * 100), max);
}
alert(max);

decze的答案是一个更好的解决方案,但我认为您也在工作。控制台中的输出示例为:

35 50 47
The greatest number is 50
undefined

未定义的部分是因为函数没有返回任何内容。你可以把它写成

var randomPrint = function(){
    x = Math.floor(Math.random() * 100);
    y = Math.floor(Math.random() * 100);
    z = Math.floor(Math.random() * 100);
   console.log(x, y, z);
   if(x > y && x > z) {
        var biggest = x;
        console.log("The greatest number is" + " " + x);
   } else if(y > z && y > x) { 
       console.log("The greatest number is" + " " + y);
       var biggest = y;
   } else if(z > y && z > x) {   
       console.log("The greatest number is" + " " + z);
       var biggest = z;
   }
   return biggest;
};
randomPrint();
        var randomPrint = function(){
    x = Math.floor(Math.random() * 100);
    y = Math.floor(Math.random() * 100);
    z = Math.floor(Math.random() * 100);
       console.log(x, y, z);
       console.log("this is max " +Math.max(x,y,z);)
}();

你的逻辑也没有错。未定义可能会出现在其他地方,这很好。

88 36 15 localhost/:16最大的数字是88

这是我得到的你的代码的输出。

相关文章: