#include <stdio.h>
double pi = 3.141592653589;
int numberOfTerms = 5;
int factorial(int n)
{
if(n > 1)
return n * factorial(n - 1);
else
return 1;
}
double DegreesToRadian(double degrees)
{
return degrees * pi/180;
}
void cosine(double cos){
int x = 0;
double ans = 1;
int exponent = 2;
int isPlus = 0;
for(x; x < numberOfTerms - 1; x++){
if(isPlus == 0){
ans -= (pow(cos, exponent))/factorial(exponent);
exponent += 2;
isPlus = 1;
}else{
ans += (pow(cos, exponent))/factorial(exponent);
exponent += 2;
isPlus = 0;
}
}
printf ("%.12f \t", ans);
}
void sine(double sin){
int x = 0;
double ans = sin;
int exponent = 3;
int isPlus = 0;
for(x; x < numberOfTerms - 1; x++){
if(isPlus == 0){
ans -= (pow(sin, exponent))/factorial(exponent);
exponent += 2;
isPlus = 1;
}else{
ans += (pow(sin, exponent))/factorial(exponent);
exponent += 2;
isPlus = 0;
}
}
printf ("%.12f \n", ans);
}
int main()
{
double j = -180.00;
printf(" ");
printf("\n\n");
for (j; j <= 180; j += 5){
printf("%.2f \t", j);
printf("%.12f \t", DegreesToRadian(j));
cosine(DegreesToRadian(j));
sine(DegreesToRadian(j));
}
return 0;
}
我使用泰勒级数来查找数字的正弦和余弦,但是当我将numberOfTerms更改为10或15时,它变得不准确(waaaaaaaaayy off),我需要更改哪些数据以使其准确? (是的,我的功能不是最优化的)当我更改numberOfTerms时,为什么我的代码不正确?
我得到一个[Warning]不兼容隐式声明内置函数'pow'(如果有的话)。
您对pi的值是错误的 - 使用math.h中的M_PI而不是自旋近似值。 (反正你也需要#include,用于'pow()'等函数)。 –
@PaulR我的学校要求不要使用math.h并使用PI近似值。 :( – CassiusDC
@PaulR:不会'atan(1)* 4'更好吗?隐式声明返回'float'的东西真的很差''math.h'在那里丢失。 –