gpt4 book ai didi

c++ - 将一系列分数的 n 次方相加并求和 - C++

转载 作者:太空宇宙 更新时间:2023-11-04 11:48:35 24 4
gpt4 key购买 nike

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

最佳答案

你不需要 for 循环:

    // 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;
}

关于c++ - 将一系列分数的 n 次方相加并求和 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19150186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com