Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Aug 2004
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    help - script does not add randomly generated numbers

    Hello,

    I am a complete beginner to javascript and would need some help. The idea is that the program generates two random numbers, adds them up and asks the user for the solution. The following script works so far that it asks the user for an input, however, it doesn't matter what number the user puts it, even if it is the right one, the loop just keeps referring to it as if the answer would be wrong. I tried var correct = 50; And if the user puts that in, the script works, so my mistake must be in the first line, but i just can't figure it out. Here is the code and thanks for the help:

    <script>

    var correct = num1 + num2;
    var guess = 0;
    var num1 = 0;
    var num2 = 0;


    num1 = Math.floor(Math.random() *100) + 1;
    // alert(num1);

    num2 = Math.floor(Math.random() *100) + 1;
    // alert(num2);

    while (guess != correct){
    guess = eval(prompt ("What is " + num1 + '' + "+" + '' + num2 + "?", ""));
    if (guess == correct){
    alert ("That's it...well done");
    } else {
    alert ("Wrong answer, please try again");
    } // end if
    } // end while

    </script>

  • #2
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Well, think about this: What is the value of num1 and num2 at the time you define correct to the value of num1+num2?

    If you move the setting of correct to be after the randomisation instead...
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #3
    New to the CF scene
    Join Date
    Aug 2004
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    omg..that easy!! Thanks it works!!


  •  

    Posting Permissions

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