简体   繁体   English

用 C 计算 Pi

[英]Calculating Pi with C

I want to calculate pi but I am getting 3.058403 as a result.我想计算 pi,但结果是 3.058403。 How can I fix this code?如何修复此代码?

#include <stdio.h>

int main(){
double x = 0;
float g =0;

printf("How many terms to calculate pi to? ");
scanf("%f", &g);

int n;
for (n = 0; n < g ; n++){
  
     double z = 1.0 / (2 * n + 1);
     if ((n % 2) == 1){
        z = z * -1;
     }
     x = (x + z);
     }
     double p = 4 * x;
    printf("The value of pi is: %f", p);
  return 0;
 }

This is not really an answer because the actual answer has been discussed in the comment section.这不是真正的答案,因为实际答案已在评论部分讨论。

Corrected version of your code:您的代码的更正版本:

  • removed pointless parentheses删除了无意义的括号
  • use meaningful variable names使用有意义的变量名
  • use of int for integer comparison使用int进行 integer 比较
  • declaration of variables as close as possible to their scope变量声明尽可能接近它们的 scope
  • code formatted properly代码格式正确
#include <stdio.h>

int main() {
  printf("How many terms to calculate pi to? ");

  int nbofterms;
  scanf("%d", &nbofterms);

  double x = 0;

  for (int n = 0; n < nbofterms; n++) {
    double z = 1.0 / (2 * n + 1);
    if (n % 2 == 1) {
      z *= -1;
    }
    x = (x + z);
  }

  double pi = 4 * x;
  printf("The value of pi is: %f", pi);
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM