Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

c - Infinite loop in program written as an exercise about finding the value of Pi

I have this assignment

The value of Pi can be determined by the following product

         2 * 2   4 * 4   6 * 6               N * N
Pi = 2 * ----- * ----- * ----- * ... * -----------------
         1 * 3   3 * 5   5 * 7         (N - 1) * (N + 1)

Write a C program that calculates the approximated value of Pi as long as the general term is greater than 1 + 10-9.

To solve it, I wrote this code:

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

int main() {
  double pi;
  const double End =
      1.0 + (1.0 / (10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0));
  double N = 2.0;

  pi = 2.0 * ((N * N) / ((N - 1.0) * (N + 1.0)));

  while (pi > End) {

    N += 2.0;
    pi *= ((N * N) / ((N - 1.0) * (N + 1.0)));
  }
  printf("%lf", pi);

  return 0;
}

I can't really understand how things work. I managed to use only double variables and added .0 to all the number literals, but the program is stuck and doesn't give any value when I launch it.

Why?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A simple solution would be to keep track of the old value, and thus replace the loop to the following (needs <math.h>)

double pi_old = pi + 1e9; // initialize to large value
while (fabs(pi-pi_old) > End){
    pi_old = pi; // store this

    // then compute next
    N += 2.0;
    pi *= ((N * N) / ((N - 1.0) * (N + 1.0)));
}

Also, As I've commented,

const double End =
      1.0 + (1.0 / (10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0));

is equivalent to

const double End = 1.0 + ( 1.0e-9 );  // 1.0e-9 = 1.0*10^(-9)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...