gpt4 book ai didi

c++ - 为用户提供循环 for 循环的选项

转载 作者:行者123 更新时间:2023-11-28 02:41:16 24 4
gpt4 key购买 nike

我无法为用户提供循环播放的选项。这个程序运行良好

#include <iostream>
using namespace std;

int main()
{
// goal is to calculate the sum of the first 10 terms of Leibniz's Series....
// calculated by 1 - 1/3 + 1/5 - 1/7 + 1/9 ..... - 1/19

int termNumber; // keeps track of term numbers
int numberOfTerms = 0;

cout << "Enter number of Terms";
cin >> numberOfTerms;


double sum = 0.0;
int sign = +1;

for (termNumber = 1; termNumber <= numberOfTerms; termNumber++)
{
sum += ( sign / (2.0 * termNumber - 1));
sign *= -1;
}

cout << "\n\n The sum is " << ( 4 * sum) << "\n\n";


} // end body of loop

如果用户愿意,我需要给用户一个重复程序的选项,所以我想我可以把它放在一个 do-while 循环中,但是当我这样做时,它只会以任何方式循环“输入术语数”尝试格式化它。这是我目前最好的。

  #include <iostream>
using namespace std;

int main()
{

// goal is to calculate the sum of the first 10 terms of Leibniz's Series....
// calculated by 1 - 1/3 + 1/5 - 1/7 + 1/9 ..... - 1/19

cout << "\nGiven a positive integer specifying some number of terms, this program\n approximates "
"pi using Leibniz' Formula and the given number of terms.\n\n" ;
cout << "Leibniz' formula is 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... = Pi / 4.\n\n";

char yes = 0;
double sum = 0.0;

do {
int termNumber; // keeps track of term numbers
int numberOfTerms = 0;


int sign = +1;
cout << "enter number of terms.\n";
cin >> numberOfTerms;

for (termNumber = 1; termNumber <= numberOfTerms; termNumber++)
{
sum += (sign / (2.0 * termNumber - 1));
sign *= -1;
}

}
while (yes = 1);
cout << "\n\n The sum is " << (4 * sum) << "\n\n";
cout << "would you like to go again? " << yes;

} // end body of loop

我想让他们选择使用 y/Y 和 n/N 有效的术语数字来尝试不同的数量。

感谢我可能得到的任何帮助。

最佳答案

你需要一个 cin 来设置 yes 而你的 cout 行在错误的地方。它们需要在您的 do while 循环中。还有一个 == 在你身上

do {
int termNumber; // keeps track of term numbers
int numberOfTerms = 0;


int sign = +1;
cout << "enter number of terms.\n";
cin >> numberOfTerms;

for (termNumber = 1; termNumber <= numberOfTerms; termNumber++)
{
sum += (sign / (2.0 * termNumber - 1));
sign *= -1;
}
cout << "\n\n The sum is " << (4 * sum) << "\n\n";
cout << "would you like to go again? " << yes;
cin >> yes
}
while (yes == 1);

试试看

关于c++ - 为用户提供循环 for 循环的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25921531/

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