java - Write a function when given one integer x ; returns e with the following approximation -


![enter image description here][1]the question:

write function name ʻ expʼ ,when given 1 integer x; returns following approximation. in function, should use previous 2 functions calculate factorial , power.

this code;

import java.util.scanner; public class ass7_q3 {     public static int power(int x, int y)     {         int result = 1;         for(int = 1; <= y; i++)         {             result = result * x;         }         return result;     }     public static int factorial(int n)     {         int fact = 1;          for(int = 1; i<= n; i++)         fact = fact * i;         return fact;     }     public static int exp( int x)     {         int result;         result = (power(x,x) / factorial(x) );         return result;     }      public static void main(string[] args) {         scanner read = new scanner(system.in);         int sum = 0;         int x;         x = read.nextint();         for(int i=0; i<=10; i++)         {             sum = sum + exp(x);         }         system.out.println(sum);     }  } 

however, when run code, gives me wrong answer.

what can do?

you should start working doubles instead of integers. can't expect approximate real number using integer calculations.

for example, power(x,x) / factorial(x) return integer, since both methods return int.


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -