Experiment 2-3-4 Find the sum of the first N items of the simple interleaved sequence (15 points)

This question requires a program to calculate the sum of the first N items in the sequence 1-1/4 + 1/7-1/10 + ...

Input format:

The input gives a positive integer N on one line.

Output format:

The partial sum value S is output according to the format of "sum = S" in one line, accurate to three decimal places. The problem is to ensure that the calculation result does not exceed the double precision range.

Sample input:

10
 

Sample output:

sum = 0.819

// It's a bit cumbersome, it can be simpler, but it's raining today, lazy, come again next time.

#include<stdio.h>
int main ()
{
    int n,i=1,sign=1;
    double sum=0,y=0;
    scanf("%d",&n);
for(i=i;n>0;n--)
    {
        y=1.0/i;
        sum=sum+sign*y;
        i=i+3;
        sign=-sign;
    }   
    printf("sum = %.3lf",sum);
    return 0;
}

Guess you like

Origin www.cnblogs.com/wven/p/12681486.html