c - 有没有更简单的方法来做到这一点?我怎样才能摆脱我的 while 循环之一?

标签 c while-loop pi

对于我的计算机科学作业,我们被要求创建一个程序来使用 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) {

一旦你这样做了,tc就完全没有必要了,可以被消除。

如果你改变了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/

相关文章:

c++ - 为什么 while (true) 在收到无效输入时会跳过 cin?

java - 如何在 while 循环中使用扫描仪

algorithm - 使用基本算法以任意精度计算 Pi

java - 在我的 Android 应用程序中使用 ffmpeg.c

c++ - 快速确定 C 预处理器分支的方法

javascript - 从循环中生成多个图像

c - 公式不正确?

c - 为什么我的文件内容消失以及如何正确读取该文件?

.net - 如何将非托管结构转换为托管结构并返回?

java - 缩放 Pi 中的 RGB 值