Help with C?

Discussion in 'Software' started by Adrynalyne, Oct 4, 2009.

  1. Adrynalyne

    Adrynalyne Guest

    I'm writing a program for class that approximates the exponential function, e^x.

    Yes, I know its already built in, but I'm supposed to do it manually to show I know how. Problem is, something doesn't work quite right and after 12 iterations, it blows up. What should happen is that each new summed value should be smaller and smaller to the point I hone in on a final value.

    Anyway, can anyone provide some help? This is what I have:

    Code:
    
    #include <stdio.h>
    #include <math.h>
    
    //factorial function prototype
    int factorial (int);
    
    
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    main ()
    {
    
    //Declaration of variables and setting of initial values
    int n,i;
    double y,ex,ugh,z;
    
    
    //take input from user for x and n
    printf("Please enter a value for the number of terms (n) and value to be approximated (x)  > ");
    scanf("%d%lf", &n, &y);
    
    //assign variable values
    ex=0;
    ugh=y;
    z=y;
    
    
    //for-loop to do e^x approximation
    for (i=0; i<=n; i=i+1)
            {
    		 ex=ex+(pow(y,i)/factorial(i)); 
            }
    
    
    
    
    //actual exp function		
    y=exp(ugh);
    
    //output
    printf("The value of exp(%g) is %g \n\n", z,y);
    printf("The approximate  value of %d terms is %g \n\n",  n+1,ex);
    }
    
    
    //factorial function
    int factorial(int n)
     {
      if (n<=1)
    	return(1);
      else
    	n=n*factorial(n-1);
    	return(n);
    }
    
     
  2. Adrynalyne

    Adrynalyne Guest

    Got it. Had to change my factorial to double.
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds