对于我的计算机科学作业,我们被要求创建一个程序来使用 Viete's Formula 来近似 pi 。我已经这样做了,但是,我不太喜欢我的代码,并且想知道是否有一种方法可以在不使用两个 while 循环的情况下做到这一点。
(我的教授要求我们使用 while 循环,所以我想至少保留一个!)
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
double n, x, out, c, t, count, approx;
printf("enter the number of iterations to approximate pi\n");
scanf("%lf", &n);
c = 1;
out = 1;
t = 0;
count = 1;
x = sqrt(2);
while (count<=n)
{
t=t+1;
while (c<t)
{
x=sqrt(2+x);
c=c+1;
}
out=out*(x/2);
count=count+1;
}
approx=2/out;
printf("%lf is the approximation of pi\n", approx);
}
我只是觉得我的代码可以更简单,但我不知道如何简化它。
最佳答案
考虑内部循环在外部循环的每次迭代中运行多少次
- 在第一次迭代中,它根本不运行 (c == t == 1)
- 在每次后续迭代中,它只运行一次(因为自外循环的最后一次迭代以来 t 已递增一次)。
所以你可以用 if 替换这个内部 while:
if (count > 1) {
一旦你这样做了,t
和c
就完全没有必要了,可以被消除。
如果你改变了x
的初始值(在循环之前),你可以让第一次迭代在这里计算它,从而也摆脱if
。这样就留下了一个最小的循环:
out = 1;
count = 1;
x = 0;
while (count<=n) {
x=sqrt(2+x);
out=out*(x/2);
count=count+1;
}
关于c - 有没有更简单的方法来做到这一点?我怎样才能摆脱我的 while 循环之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52634686/