我需要编写一个程序,添加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;
}
答案 0 :(得分: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;
}