循环-26. 求给定序列前N项和之四(15)

本题要求编写程序,计算序列 1 - 1/4 + 1/7 - 1/10 + ... 的前N项之和。

输入格式:

输入在一行中给出一个正整数N。

输出格式:

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

输入样例:

10

输出样例:

sum = 0.819
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <stdlib.h>

using namespace::std; 

int main(){
    double sum=0;
    int n,fuhao=-1;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        fuhao=-1*fuhao;
        sum=sum+fuhao*1/((i-1)*3.0+1);
    }
    printf("sum = %.3f",sum);
    return 0;
}
原文地址:https://www.cnblogs.com/ligen/p/4262270.html