1/2^1 + 1/2^2 + 1/2^3 を追加するプログラムを作成する必要があります......そして、ユーザーが行きたい n 番目の項を入力するオプションをユーザーに提供します。(2-10 の間)
分数(1/2 + 1/4 + 1/8 ....)を表示し、それらの合計を見つけて最後に表示する必要があります。(1/2 + 1/4 + 1/8 + 1/16 + 1/32 = .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;
}