Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 4 of 4

09082013, 10:27 PM #1
 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);
Thanks in advance for your help.
09082013, 10:41 PM
#2
this line:
overwrites the floor variable every time the loop iteratesCode:floor = Math.floor(Math.sqrt(i));
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:
you can read elsewhere why alert and prompt are antiquated and generally frowned uponCode:floor += Math.floor(Math.sqrt(i));
Users who have thanked xelawho for this post:
CaptainC (09082013)
09082013, 10:48 PM
#3
 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 (09082013)
09082013, 11:00 PM
#4
 Join Date
 Sep 2013
 Posts
 2
 Thanks
 2
 Thanked 0 Times in 0 Posts
Thanks to both of you! My problem is solved.