简体   繁体   中英

How to get Rid of this Nan?

I am building a dice with only Html and Javascript. I want the result of the two randomly generated number (addtion). How can I get the Result as the sum of the both number.

<!DOCTYPE html>
<html>
<head>
    <title>Dice</title>
    <h1 style="text-align:center;color:lime;font-size:300%">Dice</h1>
    <hr/>
    <br/>
    <h1 style="color: red;text-align:center;font-size:250%">You Have Got:</h1>
    <h1 style="color:gold;text-align:center;font-size:300%"><script type="text/javascript">
        var num1 = document.write(Math.floor(Math.random() * 6 + 1));
        
        document.write("<br/>");
        document.write("<br/>");

        var nu,2 = document.write(Math.floor(Math.random() * 6 + 1));
        
        document.write("<br/>");

        num1 = parseFloat(num1);
        num2 = parseFloat(num2
);
  
        document.write("<br/>");

        document.write("Result:");

        document.write(dice1 + dice2);
     </script></h1>
    <button onClick="window.location.reload();" style="font-size:200%; margin:auto;display:block;background-color:black;color:cyan">Roll Again</button>
</head>
<body style="background-color:black">
</body>
</html>

So if I run this program. I get the result as NaN. I have tried

parseInt();
parseFloat();   

Here is the Screen Shot

I would just store the numbers as separate variables, so you don't have to convert when them before adding.

<!DOCTYPE html>
<html>

<head>
  <title>Dice</title>
  <h1 style="text-align:center;color:lime;font-size:300%">Dice</h1>
  <hr />
  <br />
  <h1 style="color: red;text-align:center;font-size:250%">You Have Got:</h1>
  <h1 style="color:gold;text-align:center;font-size:300%">
    <script type="text/javascript">

      var num1 = Math.floor(Math.random() * 6 + 1);
      document.write(num1);

      document.write("<br/>");
      document.write("<br/>");

      var num2 = Math.floor(Math.random() * 6 + 1);
      document.write(num2);

      document.write("<br/>");

      //num1 = parseFloat(num1);
      //num2 = parseFloat(num2);

      document.write("<br/>");

      document.write("Result:");

      document.write(num1 + num2);
    </script>
  </h1>
  <button onClick="window.location.reload();"
    style="font-size:200%; margin:auto;display:block;background-color:black;color:cyan">Roll Again</button>
</head>

<body style="background-color:black">
</body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM