【发布时间】:2018-06-21 04:32:55
【问题描述】:
我有一个任务是编写一个程序来通过Maclaurin approximation 计算 cos(x)。但是,我必须为 cos(x) 使用一个函数,并使用另一个函数来计算 cos(x) 函数内部分母上的指数。我认为大部分内容都是正确的,但我可能遗漏了一些东西,我不知道是什么。
#include<stdio.h>
#include <stdlib.h>
#include <math.h>
int fat(int);
float cosx(float);
int main()
{
float x1;
/* Original code: **x1 = x1 * 3.14159 / 180;** `transforms the value to radians` */
x1 = x1 * 3.14159 / 180; /* transforms the value to radians */
printf("Insert number:\n");
scanf("%f", &x1);
printf("Cosine of %f = %f", x1, cosx(x1));
return 0;
}
int fat(int y)
{
int n, fat = 1;
for(n = 1; n <= y; n++)
{
fat = fat * n;
}
return fat;
}
float cosx(float x)
{
int i=1, a = 2, b, c = 1, e;
float cos;
while(i < 20)
{
b = c * (pow(x,a)) / e;
cos = 1 - b;
a += 2;
e = fat(a);
c *= -1;
i++;
}
return cos;
}
如果我输入 0,它会返回 -2147483648.000000,这显然是错误的。
【问题讨论】:
-
float x1; **x1 = ...你到底想在这里做什么? -
int fat(int y)仅适用于y <= 12,因为13!太大而无法容纳 32 位数字。 -
@JGroven 这可能是
x1 = x1 * 3.14159 / 180; /* transforms the value to radians */的格式错误。 -
如果 @Yunnosch 是正确的,那么 OP 应该知道 scanf 正在覆盖
x1的内容,除非用户以这种方式提供,否则不会将其表示为弧度。 -
将未初始化的
x1值转换为弧度后,用scanf()覆盖它(如果成功)。所以,虽然我想我知道你在那一行中做什么,但我想知道为什么你在那一行中这样做。