cam*_*boy 1 c loops pi approximation
我正在尝试制作的程序应该使用系列pi = 4*(1 - (1/3)+(1/5) - (1/7)+(1/9) - 来使用C近似pi - ( 1/11)......)等等.
现在,从命令行开始,程序必须输入用于近似的术语量,例如,如果某人从命令行输入5,则估计将达到(1/9).
问题是我的输出总是产生零,我无法确定我所做的逻辑错误.我相信这是一个for循环问题.
另外一点,我使用的是C,而不是C++.
我的代码是:
/*
Finding pi of an infinite series
*/
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(int argc, char *argv[]){ //need to get input for amount of terms
int i, pi;
pi = 0;
i = 0;
double neg; //neg to make a number negative
neg = -1;
for(i = 1; i < argc; i++)
{
pi = pi + pow(neg, i)*(1/((2*i)-1));
i = i + 1;
}
printf("The approximation of pi is: %lf", pi);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
注意:由于某种原因,它没有显示我在Stack Overflow上包含的库.我确实包括了库,我不是那么愚蠢.
(1/((2*i)-1))
Run Code Online (Sandbox Code Playgroud)
以上语句是整数,因为i是整数.整数没有小数部分,因此总是为零.由于任何时间零仍为零,因此pi将保持为零.
您应该更改为双打或浮动以获得分数答案.