Sign in with
Sign up | Sign in
Your question

What to write for this C++ program?

Last response: in Apps General Discussion
Share
Anonymous
October 25, 2009 6:28:40 AM

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-leari...

More about : write program

a b L Programming
October 27, 2009 12:49:40 AM

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.
November 13, 2009 12:01:08 PM

  1. #include <math.h>
  2.  
  3. //using a 64bit int
  4. unsigned long long factorial(int n) {
  5. unsigned long long r = 1;
  6.  
  7. if(n <= 0)
  8. return 1;
  9.  
  10. for(int i = 1; i < n; i++)
  11. r *= i;
  12.  
  13. return r;
  14. }
  15.  
  16. double sum(double x) {
  17. const double epsilon = 1e-20
  18. double sum = 1;
  19. int i = 2;
  20. double addVal = addVal = pow(x,(double)i)/factorial(i);
  21.  
  22. while(addVal > epsilon) {
  23. sum += addVal;
  24. i++;
  25. addVal = addVal = pow(x,(double)i)/factorial(i);
  26. }
  27.  
  28. return sum;
  29. }
Related resources
a b L Programming
November 13, 2009 1:03:10 PM

The factorial() function could be shortened a bit:
  1. //using a 64bit int
  2. unsigned long long factorial(int n) {
  3. unsigned long long r = 1;
  4.  
  5. while(n > 1)
  6. r *= n--;
  7.  
  8. return r;
  9. }

And for the sum() function, I would use the #defined constant instead of defining it yourself.
  1. #include <math.h>
  2. #include <float.h> // Required for DBL_EPSILON
  3. double sum(double x) {
  4. double sum = 1;
  5. int i = 2;
  6. double addVal = pow(x,(double)i)/factorial(i);
  7.  
  8. while(addVal > DBL_EPSILON) {
  9. sum += addVal;
  10. i++;
  11. addVal = pow(x,(double)i)/factorial(i);
  12. }
  13.  
  14. return sum;
  15. }

BTW, nice thinking about the EPSILON thing.
November 13, 2009 1:43:23 PM

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;
}

November 13, 2009 3:20:43 PM

@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
a b L Programming
November 13, 2009 3:27:50 PM

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.
November 13, 2009 4:51:30 PM

that could be another way to do it
!