我有一个C语言的学术项目。其中一个练习是不使用数学计算cos(x)。为此,我们给出了一个用于cos(x)的级数(我猜想它是Taylor/Maclaurin)。对于标准输入,我们有x个角度和k个迭代。之和为(-1)^n*x^(2n)/(2n)的k-1!
我尝试过在循环中和周期之外进行更改,并尝试修改变量,但没有结果。
以下是代码(更新):
#include <stdio.h>
int fat(int num) {
int fat_num=1;
for (int cnt=1; cnt<=num; cnt++) fat_num*=cnt;
return fat_num;
}
float expn(int x, int y) {
int x_y=x;
for (int cnt=1; cnt<y; cnt++) x_y*=x;
return x_y;
}
int main() {
const float pi = 3.1415926;
float x;
scanf("%f",&x);
int k;
scanf("%d", &k);
float cosx = 0;
int n = 0;
x *= pi/180;
while (n <= k-1) {
if (n%2 == 0)
cosx += expn(x,2*n)/fat(2*n);
else
cosx += -1*expn(x,2*n)/fat(2*n);
n++;
}
printf("%f", cosx);
return 0;
}
输入96的余弦值为0.54.,这是不正确的。
解决:错误在expn中,必须更新为浮动!
发布于 2019-10-12 21:47:02
两个问题
expn(x,2*n)/fat(2*n)
使用整数除法。
float expn(int x, int y)
使用int x
。需要浮点x
。
// int expn(int x, int y) {
float expn(float x, int y) {
float x_y = 1;
for (int cnt = 0; cnt < y; cnt++)
x_y *= x;
return x_y;
}
代码具有不同的效率。
一种不需要k
的替代方案--一些思考的食物。
static double my_cos_helper(double xx, double term, unsigned n) {
if (term + 1.0 == 1.0) {
return term;
}
return term - xx * my_cos_helper(xx, term / ((n + 1) * (n + 2)), n + 2);
}
double my_cos(double x) {
return my_cos_helper(x * x, 1.0, 0);
}
https://stackoverflow.com/questions/58358670
复制相似问题