Very Beginner Questions. Loops. 2nd post

here is the problem:

Quote:

Write a program that computes the following sum:

sum = 1.0/1 + 1.0/2 + 1.0/3 + 1.0/4 + 1.0/5 + .... + 1.0/N

N is an integer limit that the user enters.

Enter N

4

Sum is: 2.08333333333

here is what I have:

Code :

import java.util.Scanner;
class nSum
{
public static void main ( String[] args )
{
Scanner scan = new Scanner ( System.in );
System.out.println("Enter an integer: ");
int N = scan.nextInt();
double sum = 1.0;
double count = 0.0;
while( N > 0 )
{
count = count + 1.0;
sum = sum / count;
N = (N - 1);
}
System.out.println("The sum is: " + sum);
System.out.println("");
}
}

what am I doing wrong here? as far as I can tell the problem is within the while loop but the math looks right. when it's run, it seems to be doing integer math instead of floating point math and I have no idea why. any help would be greatly appreciated! :/

Re: Very Beginner Questions. Loops. 2nd post

Can you explain what the problem is? Add some comments that shows what you want the program's output to look like.

Re: Very Beginner Questions. Loops. 2nd post

hey thanks for the response. basically the program should just ask for an integer and print out a sum. the sum will be determined by the user like the example in the quote the user chose 4 so the program went "1.0/1 + 1.0/2 + 1.0/3 + 1.0/4 and the sum was 2.08333333333. if this would perform the math using floating point it would be correct but for some reason my code keeps using integer math dropping the remainders forcing the output to forever be 1.0 :/

Re: Very Beginner Questions. Loops. 2nd post

Look at the statement where sum is assigned a value from an expression. Does that expression look like the terms in the formula you posted?

Can you post the full console from when you execute the program?

Re: Very Beginner Questions. Loops. 2nd post

can't figure out how to copy from dos but it reads:

C:\Users\David\Desktop\Source Files>java nSum

Enter an integer:

4

The sum is: 0.04166666666664

--- Update ---

okay I got it figured out. my math was right but what was happening was the loop kept doing the same equation over and over so it wasn't adding the 1st iteration to the 2nd to the 3rd and so on and so forth to get the sum of all of them. but it works now. i can post the code if necessary. if not, consider it solved

Re: Very Beginner Questions. Loops. 2nd post