【问题标题】:Why isn't my code accurate when I change the numberOfTerms?当我更改 numberOfTerms 时,为什么我的代码不准确?
【发布时间】: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


【解决方案1】:

假设您将numberOfTerms 的值保留为10。然后,在cosinesine 函数中,在for 循环中,您每次将exponent 递增2。而且,您在分母中使用了exponent 的阶乘。

如果循环运行9 次,exponent 的值将增加为2, 4, 6, 8, 10, 12, 14, 16, 18

我们知道14! = 87178291200。但是signed int(用于返回阶乘函数的结果)最多可以保持正值2147483647。发生溢出。

我建议你使用double(甚至unsigned long long)作为阶乘函数的返回类型和参数。但不要尝试计算大数的阶乘,因为它们不适合 C 中的任何数据类型。

另外,由于您还没有自己定义 pow 函数,我认为您在顶部缺少 #include&lt;math.h&gt;

另一个建议,将pi 定义为符号常量而不是全局变量。

【讨论】:

  • 非常感谢!你是救生员。我完全忘记了整数有这样的限制。
【解决方案2】:

pow 的隐式声明返回一个 int,但实际定义返回 double,代码将逐位解释 double 和一个 int 模式,导致 完全 不正确的值 - 不仅仅是双精度的整数部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2018-05-13
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多