我需要編寫一個程序,增加了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;
}
你已經忘記了什麼每個迴路是應該做的* *。 'for'循環在一次迭代中應該做什麼? – Beta