gcc 在我的代码中,我一直得到无穷大作为输出

62lalag4  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(104)
#include <stdio.h>
#include <math.h>
int i;
double result = 0;
int terms;
int term;
double stage1;
double stage2;
double zeta(int terms){
    for (i=0; i != terms; i++){
        result += 1 / pow(i, 2);

    }
    return result;
}
double pi(int term){
    stage1 = zeta(term) * 6;
    stage2 = sqrt(stage1);
  return stage2;

}
int main(){
    printf("the terms?:");
    scanf("%d", &term);
    pi(term);
    printf("%f", pi(term));

}

我写了这个代码,使用zeta函数来计算pi,但它一直输出无穷大,无论我尝试了多少项python,它正常工作,有什么想法可以解决它吗?
我看了看它,我认为它可能是数学库,因为它确实输出了无穷大,我至少期望得到π的近似值,但它甚至没有输出,它只输出了无穷大

hyrbngr7

hyrbngr71#

代码使用Zeta函数计算π的近似值。但是,有几个问题需要解决:

Indexing and Bounds: The for loop in the zeta function should start from 1, not 0, because dividing by zero will result in undefined behavior. Additionally, the condition i != terms should be modified to i < terms to ensure the loop executes the correct number of times.

Precision: The expression 1 / pow(i, 2) performs integer division since both operands are integers. To obtain a floating-point result, you can use 1.0 / pow(i, 2) or 1 / pow(i, 2.0).

Initialization: It's good practice to initialize local variables within a function. In this case, initializing result to 0 at the beginning of the zeta function is recommended.

考虑到这几点,下面是修改后的代码:
c型

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

double zeta(int terms) {
    int i;
    double result = 0.0;
    for (i = 1; i < terms; i++) {
        result += 1.0 / pow(i, 2);
    }
    return result;
}

double pi(int term) {
    double stage1 = zeta(term) * 6;
    double stage2 = sqrt(stage1);
    return stage2;
}

int main() {
    int term;
    printf("Enter the number of terms: ");
    if (scanf("%d", &term) == 1) {
        double approxPi = pi(term);
        printf("Approximation of π: %f\n", approxPi);
    } else {
        printf("Invalid input.\n");
    }
    return 0;
}

相关问题