www.webdeveloper.com
Results 1 to 5 of 5

Thread: Addition with math.random

  1. #1
    Join Date
    May 2012
    Posts
    6

    Addition with math.random

    Title is self explanatory - I cannot figure out how to get this code working. Any help?

    HTML Code:
    <html>
    <head>
    <title> Addition </title>
    </head>
    <script>
    	
        var guess = -1; // Set guess to a value outside the range of valid values
    	var num1 = parseInt(Math.random()*10); // get a number between 0 and 9 
    	var num2 = parseInt(Math.random()*10); // get a number between 0 and 9 
    	sum = num1 + num2;
    		
        alert("(to help test) The correct answer is " + sum);  // Just to help test
    	// Use a while loop
    	while (guess != sum)
    	{
    	
    		guess = prompt("Guess a number from 1 to 10", "");
    		if (guess == sum)
    		{
    			alert("Correct!");
    			
    		}
    		else if (guess < sum)
    		{
    			alert("Guess higher ");
    		}
    		else
    		{
    			alert("Guess lower");
    		}
    	}	
                       
    </script>
    </body>
    </html>

  2. #2
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    It works. In what way does it fail for you?
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

  3. #3
    Join Date
    May 2012
    Posts
    6
    i got it

  4. #4
    Join Date
    Nov 2007
    Posts
    409
    When you pick two numbers between 1 and 10, the user is not then guessing a value between 1 and 10, the sum falls between 2 and 20 (inclusive).

    You should throw in some logic that verifies that the user entered a number between 1 and 10. Not critical, but it is odd to see "guess lower" when I enter a letter or special character instead of a number.

  5. #5
    Join Date
    May 2012
    Posts
    6
    That's true. I'll update that

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles