What to write for this C++ program?

write a program that can calculate the following sum:
S=1+((x^2)/2!)+((x^3)/3!)+((x^4)/4!)=+...+((x^n)/n!)

Read more: http://www.justanswer.com/questions/25kht-problem-learing-c-cannot-program#ixzz0UviVYCym
7 answers Last reply
More about what write program
  1. Shouldn't be that hard, why don't you give it a try before asking? Just to give you a hint, part of the solution involves the pow() function.
  2. 
    #include <math.h>
    
    //using a 64bit int
    unsigned long long factorial(int n) {
       unsigned long long r = 1;
    
       if(n <= 0)
          return 1;
    
       for(int i = 1; i < n; i++)
          r *= i;
    
       return r;
    }
    
    double sum(double x) {
       const double epsilon = 1e-20
       double sum = 1;
       int i = 2;
       double addVal = addVal = pow(x,(double)i)/factorial(i);
    
       while(addVal > epsilon) {
          sum += addVal;
          i++;
          addVal = addVal = pow(x,(double)i)/factorial(i);
       } 
    
       return sum;
    }
    
  3. The factorial() function could be shortened a bit:
    
    //using a 64bit int
    unsigned long long factorial(int n) {
       unsigned long long r = 1;
    
       while(n > 1)
          r *= n--;
    
       return r;
    }
    

    And for the sum() function, I would use the #defined constant instead of defining it yourself.
    
    #include <math.h>
    #include <float.h> // Required for DBL_EPSILON
    double sum(double x) {
       double sum = 1;
       int i = 2;
       double addVal = pow(x,(double)i)/factorial(i);
    
       while(addVal > DBL_EPSILON) {
          sum += addVal;
          i++;
          addVal = pow(x,(double)i)/factorial(i);
       } 
    
       return sum;
    }
    

    BTW, nice thinking about the EPSILON thing.
  4. I think that this can help you

    # include <iostream>
    # include <cmath>

    int main ()
    {
    float n,y=1,f,x,s=0;

    std::cout<<"Enter the number \n";
    std::cin>>n;

    for (x=1; x<=n; x++)
    {
    y=(x*y);
    f=y;
    s=s+f;

    }

    std::cout<<f;
    return 0;
    }
  5. @Zenthar the nice thing about defining the constant yourself you can choose how precise it is to tweak the speed a little bit to run faster or more precise
  6. mindless728 said:
    @Zenthar the nice thing about defining the constant yourself you can choose how precise it is to tweak the speed a little bit to run faster or more precise
    Good point.

    I also wondered if taking an optional maximum value for "n" ("i" in the code) would also be something useful. To get the rate of convergence for different values of "x" and "n" for example.
  7. that could be another way to do it
Ask a new question

Read More

Programming Apps