Topic Collection of Zhejiang University Edition "C Language Programming (3rd Edition)"
Exercise 2-14 Find the sum of the first N items in an odd-numbered fractional sequence (15 points)
This question requires writing a program to calculate the sum of the first N items of the sequence 1 + 1/3 + 1/5 + ….
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:
23
Sample output:
sum = 2.549541
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/(2*i-1);
}
printf("sum = %.6f",sum);
return 0;
}
note:
- Analyzing the question shows that the general term formula for this odd term can be written as 1/(2*i-1);
- It is known from the question that the sum of the first N terms is double type, so the numerator of the general term formula should be written as 1.0;
- Note that the output format given by the title should be kept to six decimal places, so it should be written as %.6f.