英文:
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 <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));
}
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论