系列2/3 – 4/5 + 6/7 – 8/9 +……的总和

序列是一系列数字,每个数字都有一些共同的特征。在数学中定义了各种系列,它们具有总和数学逻辑或数学公式。在这个问题中,我们得到了一系列的数字2/3,-4/5,6/7,-8/9…。

该系列的一般术语可以定义为(-1)n *(2 * n)/((2 * n)+1)

要找到级数的总和,我们需要将给定级数的每个元素相加为2/3-4/5 + 6/7-8/9 +……

让我们举个例子

Input: 10
Output: -0.191921

说明

(2 / 3) - (4 / 5) + (6 / 7) - (8 / 9) + (10 / 11) - (12 / 13) + (14 / 15) - (16 / 17) + (18 / 19) - (20 / 21) = -0.191921


Input: 17
Output: 0.77152

说明

(2 / 3) - (4 / 5) + (6 / 7) - (8 / 9) + (10 / 11) - (12 / 13) + (14 / 15) - (16 / 17) + (18 / 19) - (20 / 21) = 0.77152

示例

#include <iostream>
using namespace std;
int main() {
   int n = 17,i = 1;
   double res = 0.0;
   bool sign = true;
   while (n > 0) {
      n--;
      if (sign) {
         sign = !sign;
         res = res + (double)++i / ++i;
      } else {
         sign = !sign;
         res = res - (double)++i / ++i;
      }
   }
   cout << "The sum of the given series is "<< res;
   return 0;
}

输出结果

The sum of given series is 0.77152