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
Output sample:
sum = 2.549541
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, i, d = 1;
double sum = 0;
if (scanf("%d", &n) == 1) {
for (i = 1; i <= n; i++) {
sum += 1.0 / d;
d += 2;
}
printf("sum = %.6f", sum);
}
return 0;
}