2013-10-03 19 views
1

我需要編寫一個程序,增加了1/^ 1 + 1/2^2 + 1/2^3和......讓用戶可以選擇輸入他們希望去的第n個術語。 (間2-10)增加分數的一系列的n次冪,並尋找求和 - C++

它需要顯示的級分(1/2 + 1/4 1/8 + ....)然後找出它們的和,並顯示在末端。 (1/2 + 1/4 1/8 + 1/16 + 1/32 + = 0.96875)

我錯過在我的代碼至關重要的東西,我不知道我做錯了。在程序將它們添加到一起之前,我會讓分數顯示多次。

// This program displays a series of terms and computes its sum. 
#include <iostream> 
#include <cmath> 
using namespace std; 

int main() 
{  
    int denom,    // Denominator of a particular term  
     finalTerm,  
     nthTerm;     // The nth term 
    double sum = 0.0;  // Accumulator that adds up all terms in the series 

    // Calculate and display the sum of the fractions. 
    cout << "\nWhat should the final term be? (Enter a number between 2 and 10)"; 
    cin >> finalTerm; 

    if (finalTerm >= 2 && finalTerm <= 10) 
    { 
     for (nthTerm = 1; nthTerm <= finalTerm; nthTerm++) 
     { 
      denom = 2; 
      while (denom <= pow(2,finalTerm)) 
      { 
       cout << "1/" << denom; 
       denom *= 2; 

       if (nthTerm < finalTerm) 
        cout << " + "; 
       sum += pow(denom,-1); 
      } 
     } 
     cout << " = " << sum; 
    } 
    else 
     cout << "Please rerun the program and enter a valid number."; 

    cin.ignore(); 
    cin.get(); 

    return 0; 
} 
+1

你已經忘記了什麼每個迴路是應該做的* *。 'for'循環在一次迭代中應該做什麼? – Beta

回答

1

你並不需要循環:

// This program displays a series of terms and computes its sum. 

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

int main() 
{  
    int denom,    // Denominator of a particular term  
     finalTerm,  
     nthTerm;     // The nth term 
    double sum = 0.0;  // Accumulator that adds up all terms in the series 


    // Calculate and display the sum of the fractions. 
    cout << "\nWhat should the final term be? (Enter a number between 2 and 10)"; 
    cin >> finalTerm; 

    if (finalTerm >= 2 && finalTerm <= 10) 
    { 
     //for (nthTerm = 1; nthTerm <= finalTerm; nthTerm++) 
     //{ 
      denom = 2; 
      while (denom <= pow(2,finalTerm)) 
      { 
       cout << "1/" << denom; 
       denom *= 2; 

       if (nthTerm < finalTerm) 
        cout << " + "; 
       sum += pow(denom,-1); 
      } 
     //} 
      cout << " = " << sum << endl; 
    } 
    else 
     cout << "Please rerun the program and enter a valid number."; 

    cin.ignore(); 
    cin.get(); 

    return 0; 
} 
+0

我想你的建議,而我仍然得到加幾部分,然後它顯示總和與它幾次。我只想要一次。所以我的代碼中有一些錯誤使得它重複。任何提示或建議? – Moxy

+1

@ user2792977,什麼是for循環的目的是什麼? – cpp

+0

我本來應該使用for循環作爲練習的一部分。我想我可以按照你的建議做更多的事情,只需要把while循環變成一個for循環。似乎我的變量「nthTerm」並不是真的需要。我有我的代碼,所以這不是重複的,但它是錯誤的數學,所以我現在必須弄清楚。 – Moxy