使用 Viete 的公式在 C 中逼近 pi 的值

Approximating the value of pi in C using Viete's Formula

我这周在我的 CS class 中的任务是创建一个程序来使用 Viète 的公式来近似圆周率。过去一个小时左右,我一直在尝试开始,但老实说,我什至不确定如何开始。我已经完成的所有工作都不起作用。

我假设我的教授希望我们使用 "while" 循环,因为我们最近在 class 中经常使用它。我们也经常使用 "if" 语句,尽管我不确定我们是否需要在这里使用它们。

任何人都可以帮助我找到起点或解释我如何着手做这件事吗?

//here is some of the work i have attempted that doesn't work because i don't know what to do
#include <stdio.h> 
#include <math.h> 
#include <stdlib.h> 

int main() 

{ 
double n,pi,f,i; 

printf("enter the number of iterations to approximate for pi\n"); 
scanf("%lf\n", &n); 

pi = 2 / f; 
i = 1; 
f = sqrt(2);

while (i<=n)
{ 



}

从您发布的代码开始:

1) 您不希望 in 的类型为 double 将它们更改为 int

2) 您应该始终检查 scanf 返回的值,例如:if (scanf(%d) != 1) {// add error handling here ...}

3) pi = 2 / f; 是未定义的行为,因为 f 未初始化

那么你的作业:

我不会给你一个完整的解决方案,而是给你一个提示,这样你就可以继续你的工作。

所需的公式可以在这里找到:https://en.wikipedia.org/wiki/Viète%27s_formula#Interpretation_and_convergence

你的第一个任务是计算 a[n] 鉴于

a[1] = sqrt(2)
a[n] = sqrt(2 + a[n-1])

您可以使用 while 循环来做到这一点(尽管我更喜欢 for 循环)。它可能是这样的:

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

int main() 
{ 
    int n, i;
    n = 5;
    i = 1;
    double an = sqrt(2);

    while(i <= n)
    {
        printf("a%d = %.10f\n", i, an); 
        an = sqrt(2 + an);
        ++i;
    }
    return 0;    
}

这给你:

a1 = 1.4142135624
a2 = 1.9615705608
a3 = 1.9975909124
a4 = 1.9998494037
a5 = 1.9999905876

现在您知道如何计算 a1、a2、a3,...您只需要使用以下方法将它们放在一起:

(图片来自:https://en.wikipedia.org/wiki/Viète%27s_formula#Interpretation_and_convergence

并求圆周率。