简体   繁体   English

使用C中的递归计算pi的值

[英]Calculating value of pi using recursion in C

so I'm trying to calculate value of pi using recursion. 所以我试图使用递归来计算pi的值。 My code looks like this: 我的代码如下所示:

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

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

int main(void) {

    int n,i;
    float *A;
    scanf("%d", &n);
    A = (float*)malloc( n *sizeof(float) );
    for( i = 0 ; i < n; i++ ) {
        A[i] = pi( i + 1 );
    }
    for( i = 0; i < n; i++ ) {
        printf( "%f\n", A[i] );
    }

    return 0;
}

for value of n = 1 , it returns the expected answer, pi = 4 , but for any other value it computes that pi = 0 . 对于n = 1值,它返回期望的答案pi = 4 ,但是对于其他任何值,它都计算pi = 0 Anyone care to explain why? 有人在乎解释为什么吗?

use s = s + 4 * ( pow(-1,n+1 ) * (1.0/(2*n-1) ) ); 使用s = s + 4 * ( pow(-1,n+1 ) * (1.0/(2*n-1) ) );
instead of s = s + 4 * ( pow(-1,n+1 ) * (1/(2*n-1) ) ); 而不是s = s + 4 * ( pow(-1,n+1 ) * (1/(2*n-1) ) );
because if n=2 , the (1/(2*n-1)) part will give 1/3 , and as both 1 and 3 are integers , result will be converted to integer that is 0 , thats why u get a 0. 因为如果n = 2(1 /(2 * n-1))部分将给出1/3 ,并且由于1和3都是整数 ,结果将被转换为0的 整数 ,这就是为什么u为0的原因。

You can do it like this: 您可以这样做:

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


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

int main(void) {
    int n,i;
    float *A;
    scanf("%d", &n);
    A = (float*)malloc( n *sizeof(float) );
    for( i = 0 ; i < n; i++ ) {
        A[i] = pi( i + 1 );
    }
    for( i = 0; i < n; i++ ) {
        printf( "%f\n", A[i] );
    }

    return 0;
}

These are the things that you are doing wrong: 这些是您做错的事情:

In the function pi , you are only returning the value of s from the first recursive call. 在函数pi中 ,您仅从第一个递归调用返回s的值。 The value of s from successive recursive calls is lost. 连续递归调用中s的值将丢失。

.. ..

In this piece of code 1/(2*n-1) , since n is an integer, integer division takes place. 在这段代码1 /(2 * n-1)中 ,由于n是整数,所以发生了整数除法。 You need to cast n to a double to avoid losing digits after the floating point 您需要将n强制转换为双精度数,以避免在浮点数之后丢失数字

.. ..

The piece of code, s = s + 4 * ( pow(-1,n+1 ) * (1/(2*n-1) ) ); 这段代码s = s + 4 * ( pow(-1,n+1 ) * (1/(2*n-1) ) ); should be placed inside the if condition if( n > 0 ) This is because, when n equals 0, you will simply be adding another 4 to the value of s . 应该放在if条件if( n > 0 )这是因为,当n等于0时,您只需将s的值再加上4。

s = s +  4 * ( pow(-1, 0+1 ) * (1/(2*0-1) ) );
s = s +  4 * ( -1 * -1)
s = s +  4

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

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