我对编程还很陌生.我知道这段代码看起来也不是很好的设计.如果我不应该问这样的问题,请让我知道.我会把它记下来,然后自己解决问题(希望如此).
我的第一个使用泰勒级数计算ex的程序运行良好:
#include <stdio.h>
#include <math.h>
double calculateTaylorSeries(double x, int n) {
double result = 1.0; // The first term in the series
double term = 1.0;
for (int i = 1; i <= n; i++) {
term *= x / i;
result += term;
}
return result;
}
int main(void) {
double x;
printf("Enter the value of x: ");
scanf("%lf", &x);
int n;
printf("Enter the number of terms (n): ");
scanf("%d", &n);
double taylorApproximation = calculateTaylorSeries(x, n);
printf("e^%.2lf (approximated using %d terms): %lf\n", x, n, taylorApproximation);
return 0;
}
但对sin函数做同样的事情似乎很困难.因为有一个交替的术语方面.而权力和分母必须是奇数.
我的逻辑在我看来是正确的.但它给了我不准确的结果.
#include <stdio.h>
#include <math.h>
double calculateTaylorSeries(double x, int n)
{
double result = x;
double term = 1.0;
int sign = -1;
for (int i = 1; i <= 2 * n; i++)
{
if (i % 2 == 1)
{
term *= x / i * sign; //term = term * x/i * sign;
result += term; // result = result + term;
}
}
return result;
}
int main(void)
{
double x;
printf(" Enter the angle : ");
scanf("%lf", &x);
int n;
printf("Enter the number of terms(n):");
scanf("%d", &n);
double sinX = calculateTaylorSeries(x, n);
printf("sin(%lf) = %lf", x, sinX);
return 0;
}
以下是输出:
Enter the angle : 6.28
Enter the number of terms(n):2
sin(6.280000) = 13.146133
Enter the angle : 234
Enter the number of terms(n):15
sin(234.000000) = -49592774856964366336.000000
我还搞不懂为什么在VS代码中运行这段代码时,它会显示以下错误:
The preLaunchTask 'C/C++:gcc.exe build active file' terminated with exit code -1
.