2 Replies - 1307 Views - Last Post: 19 October 2010 - 07:09 PM Rate Topic: -----

#1 MoMahar26  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 13-January 10

Number Series Program Code Help

Posted 19 October 2010 - 06:18 PM

I am very close to finishing this, but I think I have some sort of problem with my calculations, as my output is incorrect.
Here is the problem statement:
Write a JAVA program using while loops to calculate and display the total of the following series:
1/30 + 2/29 + 3/28 + ... + 30/1

Here is what I have so far:

        double sum=0;

        int num=1;
        while(num<=30)
        {//begin of outer while loop
            int den=30;
            while(den>=1)
            {//begin of inner while loop
                sum+=(double)(num/den);
                den--;
            }//end of inner while loop
                num++;
        }//end of outer while loop
        System.out.println("The sum is "+sum); 




With this code, the output I am getting is:

run:


The sum is 1492.0
BUILD SUCCESSFUL (total time: 0 seconds)

The output is supposed to be: 93.84460106

Any help would be appreciated. Please keep in mind that I am a beginner.

Thank You!

My apologies, disregard. I meant to post this in JAVA.

Pay no attention to that bottom line, I accidentally posted this first in the VB.net forum, and just copied and pasted the original in here.

Is This A Good Question/Topic? 0
  • +

Replies To: Number Series Program Code Help

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2874
  • View blog
  • Posts: 11,047
  • Joined: 15-July 08

Re: Number Series Program Code Help

Posted 19 October 2010 - 07:07 PM

You only need one loop. Notice the pattern? The number on the bottom is 31 minus the number on top. Also note that if you divide two integers, you are performing int division, which you tried to avoid unsuccessfully. You have sum+=(double)(num/den); You need to convert either the numerator or denominator first, otherwise, it will perform the division first, THEN convert to a double. So, you can do that with your code:


double sum=0;

int num=1;
while(num<=30)
{ 
    int den= 31 - num;
    sum += ((double)num)/den;

    num++;
}
System.out.println("The sum is "+sum); 



Note that I have not tested this code, but should be giving you an accurate answer if I have done it right.
Was This Post Helpful? 0
  • +
  • -

#3 Luckless  Icon User is offline

  • </luck>
  • member icon

Reputation: 293
  • View blog
  • Posts: 1,146
  • Joined: 31-August 09

Re: Number Series Program Code Help

Posted 19 October 2010 - 07:09 PM

real simple mistake actually. make num and dem doubles instead of ints and it works fine. The error in math is an accumulation of integer divisions (basically int rounding. Happy to help :bigsmile: good job
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1