Exercise 2-15 of the Questions of Zhejiang University Edition "C Language Programming (3rd Edition)"

Exercise 2-15 Find the sum of the first N items in a simple interleaved sequence (15 points)

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

Input gives a positive integer N in one line.
Output format:
output the partial sum value S in the format of "sum = S" in one line, accurate to three decimal places. The title guarantees that the calculation result does not exceed the double precision range.
Input example:
10
Output example:
sum = 0.819
Author
C course group
Unit
Zhejiang University
Code length limit

16 KB
Time limit
400 ms
Memory limit
64 MB

#include <stdio.h>
#include <math.h>

int main() {
    
    
    int n, i, d = 1;
    double sum = 0;
    if (scanf("%d", &n) == 1) {
    
    
        for (i = 1; i <= n; i++) {
    
    
            sum += pow(-1, i + 1) * 1.0 / d;
            d += 3;
        }
        printf("sum = %.3f", sum);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/DoMoreSpeakLess/article/details/109257769