please help me to write a function with two arguments double x and int n.the function should return a value of type double and it should perform sum of following series;
1-[(x)/1!]+[(x^2)/3!]-[(x^3)/5!]+[(x^4)/7!]....upto n terms
thank you
This is a discussion on How to write a given function within the C++ Programming forums, part of the General Programming Boards category; please help me to write a function with two arguments double x and int n.the function should return a value ...
please help me to write a function with two arguments double x and int n.the function should return a value of type double and it should perform sum of following series;
1-[(x)/1!]+[(x^2)/3!]-[(x^3)/5!]+[(x^4)/7!]....upto n terms
thank you
Code:#include <iostream> #include<string.h> #include<math.h> using namespace std; int factorial(int j) { if (j==1) return 1; else return j*factorial(j-1); } double sumsequence(double x,int n){ int sign=+1; double sum=0; int term; sum +=1; for (int i =1;i<=n;i++) { sign *= -1; term = (sign * pow(x,i))/factorial(i); sum+=term; } return sum; } int main(){ double a; int b; cin >> a>>b; sumsequence(a,b); }
Cleaned up code: indented, removed unnecessary whitespace, replaced C headers with appropriate C++ headers, moved temporaries into loop instead of top of function:
Now, the problems are two-fold. First, note that (sign * pow(x, i)) / factorial(i) may not be an int! You are dividing by a number, so it may be a floating point, so you should make the temporary a double.Code:#include <iostream> #include <cmath> using namespace std; int factorial(int j) { if (j == 1) return 1; else return j * factorial(j - 1); } double sumsequence(double x, int n) { int sign = 1; double sum = 1; for (int i = 1; i <= n; i++) { sign *= -1; int term = (sign * pow(x, i)) / factorial(i); sum += term; } return sum; } int main() { double a; int b; cin >> a >> b; sumsequence(a, b); }
Secondly, the factorial(i). The formula says that the factorial shall be incremented by 2 on each iteration, but you only increment it by one.
still not working ....this is what i have now
Code:#include <iostream> #include <cmath> using namespace std; int factorial(int j) { if (j == 1) return 1; else return j * factorial(j - 1); } double sumsequence(double x, int n) { int sign = 1; double sum = 1; int k=1; for (int i = 1; i <= n; i++) { sign *= -1; double term = (sign * pow(x, i)) / factorial(k); sum += term; k+=2; } return sum; } int main() { double a; int b; cin >> a >> b; sumsequence(a, b); }
it is just returning 0.here is the screenshot of output.