Chuỗi số có quy luật chung. Số hạng chung: (-1)ⁿ * (2n) / (2n+1). Tính tổng bằng cách cộng từng số hạng.
Ví dụ:
Input: 10 Output: -0.191921
Giải thích
(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
Giải thích
(2/3) - (4/5) + (6/7) - (8/9) + ... + (34/35) = 0.77152
Ví dụ
#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;
}
Kết quả
The sum of given series is 0.77152