The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages
> Java Help
|
Homework - Please, help.
Discuss Please, help. in the Java Help forum on Dev Shed. Please, help. Java Help forum discussing all Java platforms - J2ME, J2SE and J2EE - as well as relevant standards, APIs and frameworks such as Swing, Servlets, JSPs, Applets, Struts, Spring, Hibernate, ANT, EJB, and other Java-related topics.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

November 18th, 2012, 09:19 PM
|
|
Registered User
|
|
Join Date: Nov 2012
Posts: 1
Time spent in forums: 44 m 56 sec
Reputation Power: 0
|
|
Homework - Please, help.
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!
|

November 18th, 2012, 11:10 PM
|
 |
Contributing User
|
|
|
|
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.
slink
|

November 19th, 2012, 08:04 AM
|
 |
Java Junkie
|
|
Join Date: Jan 2004
Location: Mobile, Alabama
|
|
|
One thing I notice about your code is you're adding the first term twice.
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|