PTA练习4-3 求给定精度的简单交错序列部分和 (15分)

本题要求编写程序,计算序列部分和 1 - 1/4 + 1/7 - 1/10 + ... 直到最后一项的绝对值不大于给定精度eps。

输入格式:

输入在一行中给出一个正实数eps。

输出格式:

在一行中按照“sum = S”的格式输出部分和的值S,精确到小数点后六位。题目保证计算结果不超过双精度范围。

输入样例1:

4E-2

输出样例1:

sum = 0.854457

输入样例2:

0.02

输出样例2:

sum = 0.826310

代码如下:

#include <stdio.h>
#include <math.h>
int main(){
    double eps=0;
    double sum=0,end;
    int i=1,tag=1;
    end=1.0/i;
    scanf("%lf",&eps);
    do{
        end=tag*1.0/i;
        sum=sum+end;
        i=i+3;
        tag=-tag;       
    }while(fabs(end)>eps);
    printf("sum = %.6f",sum);
    return 0;
}
发布了52 篇原创文章 · 获赞 0 · 访问量 1244

猜你喜欢

转载自blog.csdn.net/qq_38501880/article/details/104934335