Tell me what's wrong? I want to count this formula: 1 + 1/1! + 1/2! .... + 1/n! 1 + 1/1! + 1/2! .... + 1/n!

 import java.util.Scanner; public class Phill { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int x = n; int[] a = new int[n]; n = n + 1; int g = n; for (x=n-1;x < 0;x = x-1) { a[x] = g; g = g - 1; } n = n - 1; int c = 1; while (n>0) { x = 0; while(a[x] <= n) { c = a[x]*c; x=x+1; } n = n - 1; int d = 1; d = 1/c; } } } 
  • int d = 1/c; . - Igor
  • one
    System.out.println(2.718281828459045); - pavel

2 answers 2

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 
  • Thanks, of course, that you are helping, but still, this is not a solution. - Michael
  • Thank you, I'll redo it now - Mikhail

In your code you make a lot of some not very clear manipulations.

Everything is much simpler:

 int n = 10; // Количество членов ряда, считаем, что 1/1! – это первый член ряда double sum = 1; double summand = 1; for (int i=1; i<=n; i++) { summand *= ((double) 1/i); sum += summand; } System.out.println(sum);