Experiment 2-3-3 Find the sum of the first N terms in odd-numbered fractions of the sequence (15 points)

This problem requires programming, calculates the sequence 1 + 1/3 + 1/5 + ...and the first N entries.

Input format:

Enter a positive integer N in one line.

Output format:

In one line, sum = S”output the partial sum value in the format of " S, accurate to 6 digits after the decimal point. The title guarantees that the calculation result does not exceed the double-precision range.

Input sample:

23

Sample output:

sum = 2.549541

Code:

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

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

Submit screenshot:

Insert picture description here

Problem-solving ideas:

This question requires finding the Nsum of the odd-numbered part of the preceding item. Points to note:

  • Do the previous Nitem and the last item Nmean the same thing? Don’t be confused
  • This question sets up two variables iand j, among them iis a count, which means that the loop is 1traversed to N, jstarting from 1, each loop j += 2, so that sumthe value can be calculated in this way , and finally keep 6 decimal places, use%.6lf

Guess you like

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