Reputation: 29
I am trying to write a Java program to get the output of this series:
So I have done this:
import java.util.Scanner;
public class ICSE2007_Pg111 {
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter th elimit");
int n = sc.nextInt();
double add = 0;
double mult = 1;
double divide = 0;
double total = 0;
for (int i = 2; i <= n; i++) {
for (int x = 1 ; x <= i; x++) {
add += x;
mult *= x;
}
divide = add / mult;
total += divide;
}
System.out.println("The resultant sum = " + total);
}
}
I think this code is correct. However, for the value of n = 3
the correct output should be 2.916666666666666666
, but I am getting 2.25
. If someone could please pin point the error.
Upvotes: 2
Views: 50
Reputation: 803
You can do this in optimized way in one loop
float sum = 1;
float mul = 1;
float res = 0;
for(int i = 2;i<=n;i++) {
sum = sum+i;
mul = mul*i;
res = res+(sum/mul);
}
Upvotes: 0
Reputation: 393771
You forgot to reset add
and mult
before the inner loop :
for(i = 2;i<=n;i++) {
add = 0;
mult = 1;
for(x =1 ;x<=i;x++)
{
add +=x;
mult *= x;
}
...
P.S. based on your image, for n=3
you should get 2.5
.
Upvotes: 2