Exercise 2-13 of the title set of "C Language Programming (3rd Edition)" of Zhejiang University

Exercise 2-13 Find the sum of the first N items in the Nth sequence (15 points)

This question requires writing a program to calculate the sum of the first N items of the sequence 1 + 1/2 + 1/3 + ….
Input format:
Input 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 6 digits after the decimal point. The title guarantees that the calculation result does not exceed the double precision range.
Input sample:
6
Output sample:
sum = 2.450000
Author
C course group
Unit
Zhejiang University

Code length limit
16 KB
Time limit
400 ms
Memory limit
64 MB

#include <stdio.h>

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

Guess you like

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