Description
输入一个正整数 repeat (0<’repeat<10),做repeat 次下列运算:
读入 1 个正实数eps,计算并输出1-1/3+1/5-1/7+⋯⋯,直到最后一项的绝对值小于eps(保留6 位小数,不包括最后一项)。
Input
见sample
Output
见sample
Sample Input
1
1E-4
Sample Output
0.785348
#include<math.h>
#include<stdio.h>
int main()
{
int repeat;
int x;
double a,ret;
scanf("%d",&repeat);
for(int aa=0;aa<repeat;aa++)
{
ret=0;
scanf("%lf",&a);
for(int i=1;;i=i+2)
{
if(1.0/i<a)
break;
if((i/2)%2==0)
ret=ret+1.0/i;
else
ret=ret-1.0/i;
}
printf("%.6f\n",ret);
}
return 0;
}
题目要求当最后一项小于esp时输出,故构建死循环,当计算结果满足条件后break.这样方便满足”不包括最后一项”条件
至于判断加减,观察题目得:设第n项为x,当x除以二取整再取模2(即在数列中n为奇数)时,符号为正.
如此循环,得出结论;