pta Exercise 2-13 Find the sum of the first N items of the Nth sequence

Topic Collection of Zhejiang University Edition "C Language Programming (3rd Edition)"

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

Sample output:

sum = 2.450000

Code:

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

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

Operation result:
Insert picture description here
Note: The
defined sum is of double type, so the denominator should be 0.1, that is, this question should be written in the following form.
Insert picture description here

Guess you like

Origin blog.csdn.net/crraxx/article/details/109131422