c - 无法从 C 中的近似公式获得正确的输出

标签 c

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

double get_Pi(double accuracy)
{
    double Pi_estimate = 0;
    double increment = 0;
    double i = 0;
    int s = -1;


      while(fabs(increment) > accuracy)
     {

            increment = s*(1/(2*i+1));
              Pi_estimate = Pi_estimate + increment;
             s = -s;
             i++;
       }

       double offset = 1.0;
       Pi_estimate = Pi_estimate + offset;
       return 4*Pi_estimate;
       }



 int main()
{
   double accuracy;
     printf("\nhow accurate do you want Pi? ");
       scanf("%lf", &accuracy);
         double approx = get_Pi(accuracy);
       printf("%.10lf", approx);
        return 0;
      }

通过输入某个小数,您应该将 pi 变为 + 或 - 您输入的精度,但输出始终为 4.00000。

最佳答案

您从 0 而不是 1 开始,在项的分母中加法而不是减法,您正在使用整数运算而不是 float 计算 increment 的新值,并且您的while 循环永远不会进入,因为 increments 从 0 开始。

正确的公式是:pi/4 = sum(k->inf) ((-1)^(k+1))/(2k-1)

所以你会这样做:

double get_Pi(double accuracy)
{
    double Pi_estimate = 0;
    double increment;
    double i = 1;    // start at 1
    int s = 1;       // start with positive factor

    do {    // do the check at the bottom instead of the top
        increment = s*(1.0/(2.0*i-1));    // use floating point constants to prevent integer division
        Pi_estimate = Pi_estimate + increment;
        s = -s;
        i++;
    } while(fabs(increment) > accuracy);

    // no need to add an offset
    return 4*Pi_estimate;
}

关于c - 无法从 C 中的近似公式获得正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54504935/

相关文章:

C - 如何获取字符串中特定单词之后的单词?

c++ - C/C++ : Taking the address of a function imported from a shared library

c - 相同类型如何无法匹配

c - 我如何使用c解析字符串

c - 如何将用户输入的名称作为参数传递给下面给出的函数?

C pthread_join 段错误

C:数字前面的&符号

c - 如何让 gcc 生成合适的代码来检查缓冲区是否充满 NUL 字节?

objective-c - 在 mac 平台上,如何以编程方式确定用户何时通过 SSH session 登录?

c - 双 float ?使用 double 时计算错误