S = 1 1/2! 1/3! 1/4!.....
Here is my code :
import java.util.Scanner;
public class question{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
int[] fact= new int[n];
fact[0] =fact[1] =1;
for(int i=2;i<=n;i )
{
fact[i]= fact[i-1]*i;
}
double sum=0;
for(int i=1;i<=n;i ){
sum =1/fact[i];
}
System.out.println(sum);
}
}
This code is giving error input:3 Exception in thread "main" java.lang.ArrayIndexOutOfBoindsException: Index 33 out of bounds for length 3 at question.main(question.java.12)
REASON..? For this error How to resolve it..?
CodePudding user response:
The array is one element too small, it should be
int[] fact = new int[n 1];
Also note that sum =1/fact[i]
will be an integer division. You can use
sum = 1.0/ fact[i]
to get a floating point division.
CodePudding user response:
Also you do not need to store the factorials in an array as the purpose is just to sum. You could do the following:
int fact = 1;
double sum = 0;
int n = 15;
for(int i = 1; i<=n; i ){
sum = 1.0/fact;
fact *= i;
}