【发布时间】:2016-11-13 17:52:13
【问题描述】:
#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 时,它变得不准确(waaaaaaaaaayy off),我需要更改什么才能使其准确? (是的,我的功能不是最优 lel)
如果这很重要,我会收到一个 [Warning] 不兼容的内置函数“pow”的隐式声明。
【问题讨论】:
-
您的 pi 值错误 - 使用 math.h 中的 M_PI 而不是自制近似值。 (对于
pow()等函数,您还需要#include)。 -
@PaulR 我的学校要求我不要使用 math.h 并使用 PI 近似值。 :(
-
@PaulR:
atan(1)*4不是更好吗?并且隐式声明返回float的东西真的很糟糕。math.h不见了。 -
ok:newsflash:您没有使用
math.h,但您使用的是数学库中的pow。 -
不需要幂函数或阶乘函数。请看这个previous answer
标签: c