输出正弦函数的泰勒级数结果C++包含阶乘
时间: 2023-07-11 21:18:25 浏览: 114
泰勒级数仿真.zip_泰勒_泰勒级数
5星 · 资源好评率100%
好的,以下是输出正弦函数的泰勒级数结果(前10项)的C++代码,包括阶乘计算:
```c++
#include <iostream>
#include <cmath>
using namespace std;
// 计算阶乘
long long factorial(int n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
double x, result = 0;
int n;
cout << "Enter the value of x (in radians): ";
cin >> x;
cout << "Enter the number of terms to be included in the series: ";
cin >> n;
for (int i = 0; i < n; i++) {
int power = 2 * i + 1;
long long fact = factorial(power);
double term = pow(x, power) / fact;
if (i % 2 == 0) {
result += term;
} else {
result -= term;
}
}
cout << "sin(" << x << ") = " << result << endl;
return 0;
}
```
注:该代码中的阶乘计算使用了递归方式,可能在计算较大的阶乘时会出现栈溢出的问题,需要注意。
阅读全文