我需要编写一个程序,添加 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;
}