【问题标题】:C program to calculate the sine of x计算x的正弦的C程序
【发布时间】:2017-09-05 22:52:18
【问题描述】:

这是我到目前为止所做的。我不知道代码有什么问题。从理论上讲,它应该运行得很好(或者我可能错了),但事实并非如此,这让我发疯了。顺便说一句,我是初学者。

谁能指出代码有什么问题?

# include <stdio.h>
# include <conio.h>
# include <math.h>

main()
{
   int i , sum = 0 , n;
   float x;
   printf("Please enter the desired values for x and n (n>0): ");
   scanf("%f %d",&x,&n);
   for(i=1;i<=n;i++)
   {
       sum = sum +((pow(-1,i+1)*pow(x,2*i-1))/(factorial(2*i-1)));
   }
   printf("%f",sum);
}

int factorial(int n)
{
   int c;
   int result = 1;

   for( c = 1 ; c <= n ; c++ )
         result = result*c;

   return ( result );
}

【问题讨论】:

  • 这听起来像是学习使用调试器的绝佳机会。它会教你一些宝贵的技能,为你节省大量时间。
  • 要考虑的一件事是int 中可以容纳的最大值是多少。
  • sum 的类型更改为double 形式int
  • 将 int 更改为双重工作。
  • 您可以按照@JonathanLeffler 的建议将x、n、总和全部更改为两倍。这将使其不易溢出。此外,如果您有任意输入 x,则需要对参数进行归约。否则,收敛速度会非常缓慢,以至于无法获得远程正确的答案。

标签: c series trigonometry


【解决方案1】:

主要问题:

  • sum 类型应该是floatdouble,而不是int
  • factorial(int n) 必须能够返回很大的数字,所以它的返回类型也应该是 double

可能的解决方案:

# include <stdio.h>
# include <math.h>

double factorial(int n)
{
    if (n == 0) return 1;
    return n * factorial(n-1);
}
main()
{
    int n;
    double x, sum = 0;
    printf("Please enter the desired values for x and n (n>0): ");
    scanf("%lf %d", &x, &n);
    for(int i = 0; i <= n; i++)
    {
        sum += pow(-1, i) * pow(x, 2 * i + 1) / (factorial(2 * i + 1));
    }
    printf("%f", sum);
}

为了使您的正弦计算器防弹,您应该添加一些行来检查输入 x 的值,并在评估系列之前至少将其减少到域 [-pi, pi]。 查看我的回答 herehere 以了解原因。

【讨论】:

    【解决方案2】:

    @Busy Beaver 好的答案指出了 OP 代码中的一些缺陷。

    但要深入了解 OP 如何在没有 Stack Overflow 的情况下解决这个问题。

    谁能指出代码有什么问题?

    与其寻求帮助,不如先使用您的编译器。启用所有编译器警告。一个好的编译器会抱怨下面的事情。这比在 SO 上发布更快的反馈。

    // return type defaults to 'int' 
    main()
    // this should be as below  (amongst other possibilities)
    int main(void)
    
    // implicit declaration of function 'factorial'
    sum = sum +((pow(-1,i+1)*pow(x,2*i-1))/(factorial(2*i-1)));
    // factorial should be declared/defined before it it used
    
    // conversion to 'int' from 'double' may alter its value
    sum = sum +((pow(-1,i+1)*pow(x,2*i-1))/(factorial(2*i-1)));
    // This is the hint that `sum` should also be a floating point.
    
    // format '%f' expects argument of type 'double', but argument 2 has type 'int'
    printf("%f",sum);
    // sum is type `int`, the matching specifier is "%d"`.
    

    通过修复这些警告,代码“工作”而无需其他更改。 factorial() 计算仍然存在精度、范围有限、效率和溢出等问题。经验教训:使用您的编译器来帮助解决基本问题。

    Please enter the desired values for x and n (n>0): 1 5
    0.841471
    

    我现在看到这是一个旧帖子,并且 OP 可能有 left the building

    【讨论】:

      猜你喜欢
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      相关资源
      最近更新 更多