0

...しかし、コンソールで関数を呼び出すと、未定義が返されます。私は 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();
4

5 に答える 5

1

この組み込みの方法を試して、最大値を取得してください

Math.max(x,y,z);
于 2013-09-04T07:15:04.440 に答える
1

残りの 2 つの数字を捨てることができる場合:

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

alert(max);
于 2013-09-04T07:18:11.107 に答える
0

deceze からの答えはより良い解決策ですが、あなたもうまくいっていると思います。コンソールの出力例は次のとおりです。

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();
于 2013-09-04T07:17:07.007 に答える
0
        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);)
}();

あなたの論理も間違っていません。undefined が別の場所に来る可能性があることは問題ありません。

88 36 15 localhost/:16 最大数は 88

これは私が得たコードの出力です。

于 2013-09-04T07:17:57.653 に答える