求多項式 1 - 1/2 + 1/3 - 1/4 + ... 前n項的值
阿新 • • 發佈:2018-11-04
Problem Description
多項式的描述如下:
1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + …
現在請你求出該多項式的前n項的和。
Input
輸入資料由2行組成,首先是一個正整數m(m<100),表示測試例項的個數,第二行包含m個正整數,對於每一個整數(不妨設為n, n<1000),求該多項式的前n項的和。
Output
對於每個測試例項n,要求輸出多項式前n項的和。每個測試例項的輸出佔一行,結果保留2位小數。
Sample Input
2
1 2
Sample Output
1.00
0.50
參考程式碼如下:
#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { int m,n,i; float s; while(cin>>m) { while(m--) { s=0; cin>>n; for(i=1; i<=n; i++) s += ( 1 / ( ( pow( (-1), (i+1) ) ) * i ) ); // 相當於乘以(-1)的i+1次方 cout << setiosflags(ios::fixed) << setprecision(2) << s; cout << endl; } } return 0; }
其中setiosflags() , setprecision()函式在我轉載的一篇博文裡面有詳細講解
https://blog.csdn.net/weixin_43469047/article/details/83422790