在 C 中递归计算 PI [英] Calculating PI recursively in C

查看:60
本文介绍了在 C 中递归计算 PI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可能有更好的计算 PI 的方法,但自从我找到了莱布尼茨公式:

I understand there are probably much better ways of calculating PI, but since I found the Leibniz formula:

我决定使用递归在 C 中实现它:

I decided to implement it in C using recursion:

double pi(int n){
    if(n==1)return 4;
    return 4*pow(-1,n+1)*(1/(2*n-1))+pi(n-1);
}

当我调用该函数时,我总是得到 4.000000,这意味着它仅适用于数字 1;每个其他数字都会给我相同的结果.

What I always get when I call the function is just 4.000000, meaning it works for number 1 only; Every other number gives me the same result.

我想知道为什么这个解决方案不能正常工作.我试过在纸上写下不同数字的每一步,其背后的逻辑似乎是正确的.

What I'm wondering is why this solution isn't working properly. I've tried writing every step down on paper for different numbers and the logic behind it seems correct.

除了答案中提供的内容(谢谢!),似乎 (1/(double)(2*n-1)) 而不是 (1/(2*n-1)) 也解决了问题.

Except for what was provided in the answer (thank you!) it seems like (1/(double)(2*n-1)) instead of just (1/(2*n-1)) fixed the problem as well.

推荐答案

错误完全出在这个词条上:

The error is entirely in this term:

(1/(2*n-1))

假设在这次迭代中 n 恰好是 3:

Say that n happens to be 3 in this iteration:

1 / (2 * 3 - 1) == 1 / 5 == 0

(当你认为结果应该是 0.2 时,我会让你弄清楚为什么结果是 0)

提示 #1:1.01 有什么区别?

提示 #2: 如何通过向表达式添加单个字符来修复表达式:.??

1 的类型为 int1.0 的类型为 double
将表达式更改为 (1./(2*n-1))

1 has type int, 1.0 has type double
Change the expression to be (1./(2*n-1))

这篇关于在 C 中递归计算 PI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆