2014-10-22 32 views
-1

首次編程時,我必須編寫一個程序來計算系列方程 (n!)^ 2 * 2^n + 1 /(2n + 1)!,n即用戶輸入的條款數量。需要計算收斂到π的系列方程

我已經知道用戶輸入n的位置,我只能得到該號碼的答案。

如何製作它以便我可以從0到用戶輸入中獲得所有答案的總和?

#include <iostream> 
#include<cmath> 

using namespace std; 

int main() 
{ 

    double i,n,factorial,factorial2,n2,a; 
    a = 1; 
    cout<<"Enter # of terms:"; 
    cin>>n; 

    for (i = 0; i <= n; i++) 

    if (i == 0) 
     factorial = 1; 
    else 
     factorial = factorial * i; 

    factorial = pow(factorial,2)*pow(2,n+1); 

    n2 = 2*n+a; 

    for (i = 0; i <= n2; i++) 

    if (i == 0) 
    factorial2 = 1; 
    else 
    factorial2 = factorial2 * i; 
    factorial = factorial/factorial2; 

    cout<<factorial<<endl; 
    system("PAUSE"); 
} 
+1

等待... *什麼*不向用戶提供? – Beta 2014-10-22 05:15:54

+2

「獲取用戶輸入的所有術語的總和?」 - 不知道你爲什麼要這樣做,但是這聽起來像'double n,total = 0; while(std :: cin >> n)total + = n; std :: cout <<「total」<< total <<'\ n';'。 – 2014-10-22 05:16:38

+0

n條款。那麼用戶輸入爲4,得到方程中4,3,2,1和0的結果之和? – jim 2014-10-22 05:35:15

回答

0

你有兩個選擇:

  • 使用一個循環,將通過每個n
  • 做一個遞歸函數:

    // In pseudocode 
    term (n){ 
    if (n < 0) return 0; 
    
    // calculate y for this n; 
    return y + term(n - 1); 
    } 
    

遞歸函數(假設你熟悉函數)是調用自身解決問題的功能。例如,n! =(n - 1)! * n。您可以使用這個簡單的事實創建一個返回n * f(n - 1)的因子函數f(n),除非n是1(在這種情況下返回1)。

,我會制定了第一個選項:

// I assumed your code is working and that factorial holds the values you want to sum. 
// If that's not the case, I believe you can use it to solve your problem anyway 

#include <iostream> 
#include<cmath> 
using namespace std; 

int main() { 
    double n, total = 0; 
    cout << "Enter # of terms:"; 
    cin >> n; 

    while (n >= 0) { 
     double i, factorial, factorial2, n2, a; 

     a = 1; 

     for (i = 0; i <= n; i++) { 
      if (i == 0) 
       factorial = 1; 
      else 
       factorial = factorial * i; 
     } 

     factorial = pow(factorial, 2)*pow(2, n + 1); 

     n2 = 2 * n + a; 

     for (i = 0; i <= n2; i++) { 
      if (i == 0) 
       factorial2 = 1; 
      else 
       factorial2 = factorial2 * i; 

      factorial = factorial/factorial2; 
     } 

     total += factorial; 
     n--; 
    } 
    cout << total << endl; 
} 

希望它能幫助:d

0

下面是從我的意見的代碼,所有的佈局是可讀......

#include <iostream> 
#include <cmath> 

int factorial(int n) 
{ 
    return n <= 1 ? 1 : factorial(n - 1) * n; 
} 

或者如果你發現這個階乘函數令人困惑,SlySherZ建議這個初學者友好的替代方案(你不需要這兩個實現)。

int factorial(int n) 
{ 
    if (n <= 1) 
     return 1; 
    return factorial(n - 1) * n; 
} 

繼續...

double f(double n) 
{ 
    return std::pow(fact(n),2) * std::pow(2, n) + 1/factorial(2 * n + 1); 
} 

int main() 
{ 
    double n, total = 0; 
    while (std::cin >> n) 
     total += f(n); 
    std::cout << "total " << total << '\n'; 
}