我代码的输出一直是无穷大。

huangapple go评论60阅读模式
英文:

i keep getting infinity as an output in my code

问题

I wrote this code that uses the zeta function to calculate pi, but it keeps outputting infinity no matter how many terms I try. I tried Python, and it works normally there. Any ideas on how to fix it?

I looked into it, and I think it might be the math library because it does output infinity. I was at least expecting an approximation of pi, but it did not even output that; it just outputted infinity.

英文:
#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));

}

i wrote this code that uses the zeta function to calculate pi but it keeps outputting infinity no matter how many terms i tried python and it works normally there any ideas on how to fix it?

i looked into it and i think it might be the math library because it does output infinity i was at least expecting an approximation of pi but it did not even output that it just outputted infinity

答案1

得分: 0

尝试:

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

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

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

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

我只修改了 for 循环,从1开始而不是从零开始(大致了解了 zeta 函数,希望我理解正确 - 如果我在这里错了,对不起)。

我还将变量移到了函数内部(即它们被使用的地方),这是您应该始终要做的。您会注意到,即使在 zeta 函数中,变量 i 也是在更窄的范围内声明的(for 循环范围,而不是函数范围)。

英文:

Try:

#include &lt;stdio.h&gt;
#include &lt;math.h&gt;

double zeta(int terms)
{
    double result = 0;
    for (int i = 1; i &lt; terms; i++)
        result += 1 / pow(i, 2);
    return result;
}

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

int main()
{
    int term;
    printf(&quot;the terms: &quot;);
    scanf(&quot;%d&quot;, &amp;term);
    printf(&quot;%f\n&quot;, pi(term));
}

I only changed the for loop, starting from 1 instead of zero (reading briefly about the zeta function, I hope I understood it - sorry if I am wrong here).

I also moved variables inside functions (= the place where they are used), something you should always do. You will note that even the variable i in zeta function is declared in a narrower scope (the for loop scope, not the function scope).

huangapple
  • 本文由 发表于 2023年5月18日 00:54:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76274483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定