gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:52:56 24 4
gpt4 key购买 nike

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

我假设我的教授希望我们使用“while”循环,因为我们最近在类里面经常使用它。我们也经常使用“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,...您只需要使用以下方法将它们放在一起:

enter image description here

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

并找到 pi。

关于c - 使用 Viete 的公式在 C 中逼近 pi 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52619552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com