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 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Sep 2013
    Posts
    2
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Help with a simple for loop function

    In my program, the user enters an integer. Using this integer as the upper limit, the program calculates the sum of the floors of the square roots of each integer from 1 to the supplied integer. I am making use of a for loop in my program, but am having trouble getting the desired result. Here is my current setup:
    Code:
    var max = Number(prompt("enter an integer"));
    var floor;
    for (i=1; i<=max; i++) {
    floor = Math.floor(Math.sqrt(i));
    }
    alert("the sum of the floors of the square roots of each integer from 1 to " + max + " is " + floor);
    When I run this with 4 as the supplied integer, the program gives me 2 as the answer. However, 5 is the actual correct answer (Math.floor(Math.sqrt(1))+Math.floor(Math.sqrt(2))+ Math.floor(Math.sqrt(3))+Math.floor(Math.sqrt(4)) produces 1+1+1+2, which is 5). What am I doing wrong?

    Thanks in advance for your help.

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,883
    Thanks
    56
    Thanked 539 Times in 536 Posts
    this line:
    Code:
    floor = Math.floor(Math.sqrt(i));
    overwrites the floor variable every time the loop iterates

    if you want to be adding the result, initialize floor as 0 and then add the result of your calculation to it on each iteration:

    Code:
    floor += Math.floor(Math.sqrt(i));
    you can read elsewhere why alert and prompt are antiquated and generally frowned upon

  • Users who have thanked xelawho for this post:

    CaptainC (09-08-2013)

  • #3
    Senior Coder
    Join Date
    Sep 2010
    Posts
    1,903
    Thanks
    15
    Thanked 226 Times in 226 Posts
    Code:
    var max = Number(prompt("enter an integer"));
    var floor=0;
    for (i=1; i<=max; i++) {
    floor = floor + Math.floor(Math.sqrt(i));
    }
    alert("the sum of the floors of the square roots of each integer from 1 to " + max + " is " + floor);
    Welcome to http://www.myphotowizard.net

    where you can edit images, make a photo calendar, add text to images, and do much more.


    When you know what you're doing it's called Engineering, when you don't know, it's called Research and Development. And you can always charge more for Research and Development.

  • Users who have thanked DrDOS for this post:

    CaptainC (09-08-2013)

  • #4
    New to the CF scene
    Join Date
    Sep 2013
    Posts
    2
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Thanks to both of you! My problem is solved.


  •  

    Posting Permissions

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