Advertisement
electricmaster

factorial2.c

Oct 13th, 2015
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. float factorial(int n){ // x!
  5.   if(n == 0) return 1;
  6.   else if(n < 0) return -1;
  7.   int i = 1;
  8.   int x = 1;
  9.   for(i = 1; i <= n; i++) x = (float) x*i;
  10.   return x;
  11. }
  12.  
  13. float etaylor(int n){ // e = Σ1/(x!)
  14.   if(n < 0) return -1;
  15.   float x = 0;
  16.   int i = 1;
  17.   for(i = 1; i <= n; i++) x = x+(1.0/factorial(i));
  18.   return x;
  19. }
  20.  
  21. float extaylor(int x, int n){ // e^x = Σx/n!
  22.   if(x < 0 || n < 0) return -1;
  23.   int i = 0;
  24.   float y = 0;
  25.   for (i = 0; i <= (n-1); i++) y = y + pow(x,i)/factorial(i);
  26.   return y;
  27. }
  28.  
  29. int main(){
  30.   int n, s, x;
  31.   printf("WELCOME TO MY TAYLOR SERIES DUNGEON!!!1!!\n");
  32.   printf("PLEASE SELECT YOUR CHALLENGE:\n");
  33.   printf("1. y = x!\n");
  34.   printf("2. e = E1/x!\n");
  35.   printf("3. e^x = E[(x^k)/k!]\n");
  36.   printf("Your selection: "); scanf("%d", &s);
  37.   switch(s){ // Choose selection
  38.     case 1: {
  39.       printf("\nx = "); scanf("%d", &x);
  40.       printf("\ny = %f", factorial(x));
  41.       return 0;
  42.     }
  43.     case 2: {
  44.       printf("\n x = "); scanf("%d", &x);
  45.       printf("\n e = %f", etaylor(x));
  46.       return 0;
  47.     }
  48.     case 3: {
  49.       printf("\n x = "); scanf("%d", &x);
  50.       printf("\n Upper bound k = "); scanf("%d", &n);
  51.       printf("\n e^%d = %f", x, extaylor(x, n));
  52.       return 0;
  53.     }
  54.     default: {
  55.       printf("Invalid selection %d", s);
  56.       return -1;
  57.     }
  58.   }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement