First, this cycle does not make sense.
for (x=n-1;x < 0;x = x-1){ ^^^^^
since initially, as I understand it, the value of x is positive. therefore, the cycle will never be executed due to the condition x < 0 .
Also there is no point in these sentences.
x = 0; while(a[x] <= n) { c = a[x]*c; x=x+1; } n = n - 1; int d = 1; ^^^^^^^^^ d = 1/c; ^^^^^^^^^ }
You declare a local variable d at the end of the loop body, and this variable is immediately destroyed.
Keep in mind that to store calculations using your formula, you need to declare variables as floating-point numbers and calculate expressions accordingly. Also note that integers are limited, and therefore they can store factorial only for a limited value.
You have a lot of meaningless code in the program, like, for example, this
n = n + 1; ^^^^^^^^^^ int g = n; for (x=n-1;x < 0;x = x-1) { a[x] = g; g = g - 1; } n = n - 1; ^^^^^^^^^^
Instead of two highlighted sentences, you could just write
int g = n + 1;
EDIT: I’m not good at Java (that is, I don’t know it at all), as in other programming languages, but using common sense, I would write the program as follows
import java.util.*; import java.lang.*; import java.io.*; class Demo { private static double calculate( int n ) { double result = 0.0; double factorial = 1.0; for ( int i = 0; i <= n; i++, factorial /= i ) { result += factorial; } return result; } public static void main (String[] args) throws java.lang.Exception { int n; Scanner scan = new Scanner( System.in ); do { n = 0; System.out.print( "Enter a non-negative number: " ); n = scan.nextInt(); } while ( ! ( n > 0 ) ); System.out.println( "The result is equal to " + calculate( n ) ); } }
If you enter the number 10 , the result will be as follows
Enter a non-negative number: 10 The result is equal to 2.7182818011463845
int d = 1/c;. - IgorSystem.out.println(2.718281828459045);- pavel