solution.md 1.7 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4
# 求分数数列的前N项和

有一分数序列:2/1,-3/2,5/3,-8/5,13/8,-21/13,…, 由用户输入项目数N,求这个数列的前N 项之和

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
以下程序实现了这一功能,请你填补空白处内容:

```cpp
#include <stdlib.h>
#include <stdio.h>
int main()
{
    int n;
    scanf("%d", &n);
    int i;
    double a1 = 2, b1 = 1;
    double a2 = 3, b2 = 2;
    double sum = a1 / b1 - a2 / b2;
    if (n == 1)
        printf("%f\n", a1 / b1);
    else if (n == 2)
        printf("%f\n", sum);
    else
    {
        for (i = 0; i < n - 2; i++)
        {
            double exp = a2 / b2;
            _____________________
            sum += exp;
            double a = a1 + a2;
            double b = b1 + b2;
            a1 = a2;
            b1 = b2;
            a2 = a;
            b2 = b;
        }
        printf("%f\n", sum);
    }
    return 0;
}
```

每日一练社区's avatar
每日一练社区 已提交
42 43 44
## template

```cpp
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
#include <stdlib.h>
#include <stdio.h>
int main()
{
    int n;
    scanf("%d", &n);
    int i;
    double a1 = 2, b1 = 1;
    double a2 = 3, b2 = 2;
    double sum = a1 / b1 - a2 / b2;
    if (n == 1)
        printf("%f\n", a1 / b1);
    else if (n == 2)
        printf("%f\n", sum);
    else
    {
        for (i = 0; i < n - 2; i++)
        {
            double exp = a2 / b2;
            if (i % 2 == 0)
                exp *= -1;
            sum += exp;
            double a = a1 + a2;
            double b = b1 + b2;
            a1 = a2;
            b1 = b2;
            a2 = a;
            b2 = b;
        }
        printf("%f\n", sum);
    }
    return 0;
每日一练社区's avatar
每日一练社区 已提交
77 78 79 80 81 82
}
```

## 答案

```cpp
83 84
if (i % 2 == 0)
    exp *= -1;
每日一练社区's avatar
每日一练社区 已提交
85 86 87 88 89 90 91
```

## 选项

### A

```cpp
92 93
if (i % 2 == 0)
    exp = -1;
每日一练社区's avatar
每日一练社区 已提交
94 95 96 97 98
```

### B

```cpp
99 100
if (i / 2 == 0)
    exp *= -1;
每日一练社区's avatar
每日一练社区 已提交
101 102 103 104 105
```

### C

```cpp
106 107
if (i / 2 == 0)
    exp = -1;
每日一练社区's avatar
每日一练社区 已提交
108
```