This question requires the preparation of program that calculates the sequence 2/1+3/2+5/3+8/5+...
of front N
and Paragraph. Note that the sequence starts from the first 2
item, the numerator of each item is the sum of the previous item's numerator and the denominator, and the denominator is the previous item's numerator.
Input format:
Enter a positive integer in one line N
.
Output format:
Output the partial sum value in one line, accurate to two decimal places. The title guarantees that the calculation result does not exceed the double precision range.
Input sample:
20
Sample output:
32.66
Code:
# include <stdio.h>
# include <stdlib.h>
int main() {
int N;
scanf("%d",&N);
double value = 0.0,a = 1.0,b = 2.0,temp;
// a和b分别代表分母和分子
int i = 1;
while (i <= N) {
value += (b / a);
// 第(i+1)分母 == 第i分子,第(i+1)分子 = 第i分母 + 第i分子
temp = b;
b += a;
a = temp;
i += 1;
}
printf("%.2lf",value);
return 0;
}
Submit screenshot:
Problem-solving ideas:
The mathematical idea of this question is Fibonacci 纳妾
(O(∩_∩)O). It was originally used to study the problem of rabbit reproduction. Now it is a PAT
practice problem to change it ! The following divides the fraction into numerator and denominator to understand:
- molecular:
2 3 5 8
- Denominator:
1 2 3 5
We can find out第(i+1)分母 == 第i分子,第(i+1)分子 = 第i分母 + 第i分子
, so we can easily write the code!