Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
November 18th, 2012, 10:19 PM
 Daler
Registered User

Join Date: Nov 2012
Posts: 1
Time spent in forums: 44 m 56 sec
Reputation Power: 0

Hey guys,

I have a little problem here. The program runs and everything is fine except the actual result. The question is:

Design Java code to calculate and print ∑ (n! + 5) / (n+1)! ; n is an integer from 1 to 10.

I have written the code and I it's here:

Quote:
 /** *Question #2 */ public class Sum { public static void main (String [] args) { long a = 1; long b = 2 * a; double sum = (a + 5.0) / b; long n = 3; while(n<=11) { sum = sum + (double)(a + 5.0) / b; b = n * b; a = a * (n - 1); //probably mistake here n++; }//end of a loop System.out.println("The answer is " + sum); } }

I checked on my calculator and the result is 5.611286476

But my output is 8.520377259700176

Please, guys. I don't know where should I go. Help me find my mistake!

#2
November 19th, 2012, 12:10 AM
Contributing User

Join Date: Nov 2010
Posts: 73
Time spent in forums: 1 Day 17 h 10 m 20 sec
Reputation Power: 15
Hi Daler,

The trick with programming is to keep things simple. Instead of trying to do everything in one go, try separating things out into functions. For example, you are using factorials, so break that out into a function:

Code:
```public static long factorial(long x) {
long factorial = 1;
for (int i = 1; i <= x; i++) {
factorial *= i;
}
return factorial;
}```

Then you can use that in your main method.

It is generally better to write code that is easily understood (and debugged) than something that is perfectly optomized.

Hope this helps.

#3
November 19th, 2012, 09:04 AM
 bullet
Java Junkie

Join Date: Feb 2004
Location: Mobile, Alabama
Posts: 3,961
Time spent in forums: 1 Month 2 Weeks 1 Day 7 h 12 m 30 sec
Reputation Power: 1283

 Viewing: Dev Shed Forums > Programming Languages > Java Help > Homework - Please, help.