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

This problem requires programming, calculates the sequence 1 - 1/4 + 1/7 - 1/10 + ...and the first N entries.

Input format:

Enter a positive integer N in one line.

Output format:

In one line, sum = Soutput the partial sum value S in the format of " ", accurate to three decimal places. The title guarantees that the calculation result does not exceed the double precision range.

Input sample:

10

Sample output:

sum = 0.819

Code:

# include <stdio.h>
# include <stdlib.h>

int main() {
    
    
    int N,i,j = 1,m = 1;
    double sum = 0.0;
    scanf("%d",&N);
    for (i=1;i<=N;i++) {
    
    
        sum += (1.0 / m)*j;
        j *= (-1);
        m += 3;
    }
    printf("sum = %.3lf",sum);
    return 0;
}

Submit screenshot:

Insert picture description here

Problem-solving ideas:

This question is an extension of the above two questions, you need to pay attention to:

  • Interval change number, so every cyclej *= (-1)
  • The absolute value of the denominator of each two terms is separated by 3, so every cyclem += 3
  • Finally, sum = 0.0it must be initialized

Guess you like

Origin blog.csdn.net/weixin_43862765/article/details/114388833