The risk with using a factorial function is that it very quickly goes out of int
range. There is no need to have either a power function or a factorial function, because each term of the Taylor series can be derived from the previous term, by using a multiplication and a division.
The multiplier is self-evident, simply the square of the angle.
The divisor is i * (i - 1)
, the next two terms of the factorial.
You will see I have removed your sign change factor t
, because to change the sign of the previous term from neg to pos, or pos to neg, you just multiply by -1
. But I have even removed that by reversing the sign of (i - 1)
with my use of (1 - i)
.
The first term of the series is simply rad
so I start with that.
#include <stdio.h>
#include <math.h>
int main()
{
int n, i; // don't use `l` for a variable name
float deg, rad, radsq, val, term;
printf("Enter degree of sin: ");
if(scanf("%f", °) != 1) {
return 1; // or other error handling
}
printf("Enter limit of Taylor series: ");
if(scanf("%d", &n) != 1) {
return 1; // or other error handling
}
rad = deg * 3.14159265f / 180; // proper value for pi
radsq = rad * rad;
term = rad; // first term is rad
val = term; // so is series sum
for(i = 3; i <= n; i += 2) // we've done the first term
{
term *= radsq / (i * (1 - i)); // see explanation
val += term; // sum the series
}
printf("
Value calculated by program, using Taylor Series:
");
printf("Sin(%f) = %f
", deg, val);
printf("
Value calculated using library function:
");
printf("Sin(%f) = %f
", deg, sin(rad));
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…