該程序應該添加1/2^1 + 1/2^2 + 1/2^3 .... 1/2^n(用戶輸入n次冪)。它應顯示分數(1/2 + 1/4 + 1/8 ....),然後找到它們的總和,並在結尾處顯示總和(例如:1/2 + 1/4 + 1/8 =。 125) 它在用戶輸入5時有效,但其他任何數字顯示錯誤的總數。我得到的總和大於1,這是不正確的。我怎樣才能解決這個問題?C++如何計算總分數的總和?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int denom, // Denominator of a particular term
finalDenom, // Denominator of the final term
nthTerm; // Nth term run
double sum = 0.0; // Accumulator that adds up all terms in the series
char repeat;
do
{
cout << "This program sums the series 1/2^1 + 1/2^2 + 1/2^3 + . . . + 1/2^n\n";
cout << "What should n be in the final term (between numbers 2 and 10)? ";
cin >> finalDenom;
nthTerm = 0;
for (denom = 2; nthTerm <= (finalDenom - 1); denom *= 2)
{
cout << "1/" << denom;
++nthTerm;
if (denom != finalDenom)
{
cout << " + ";
}
else if (denom == finalDenom)
{
cout << " = ";
}
sum += pow(denom, -1);
}
cout << sum << endl << endl << endl;
cout << "Do you wish to compute another series? ";
cin >> repeat;
repeat = toupper(repeat);
} while ((repeat == 'Y'));
return 0;
}
歡迎堆棧溢出!這聽起來像你可能需要學習如何使用調試器來遍歷代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:** [如何調試小程序](http:// ericlippert。com/2014/03/05/how-to-debug-small-programs /)** –
'和'sum + = pow(denom,-1);'太多了:只要做'sum + = 1.0/denom ;' –
@BaummitAugen:對!我讀** 2,但不能在C中完成。對不起...對不起...... –