Write a program that takes as input two numbers n (integer) and x (double), and prints arctan(x) evaluated by taking n terms of the Taylor series (using x0 =0):
arctan(x) = x - x 3 /3 + x 5 /5 - x 7 /7 …
To care of numerical accuracy and rounding off we have created a print(x) function. Please use this to print your final answer. Suppose your answer is in a variable called ans, then print it to screen using “print(ans);” and NOT “cout << ans;”.
Please print a newline( using “cout<<endl;” is one way to do it) after printing your answer
#include <iostream>
#include <cmath>
using namespace std;
void print (float answer) {
cout << answer;
}
int main () {
int n, p = 1;
double x, S = 0;
cout << "n = "; cin >> n;
cout << "x = "; cin >> x;
for (int i = 1; i < n; i++) {
if (i % 2 == 1) {
S += p * pow(x, i) / i;
p *= (-1);
}
}
float ans = S;
cout << "arctan(" << x << ") = ";
print(ans);
return 0;
}
Comments
Leave a comment