我正在编写一个程序,必须为此使用嵌套循环来执行用户输入的许多抛硬币操作。我已经设定了一个哨兵值,如果用户没有输入哨兵值,那么程序将重复执行。现在,我有一个无限循环要尝试摆脱,但我的问题是while循环对于该程序是否是最佳选择。
for循环是更好的选择吗?这段代码有点混乱,但我仍在努力。 我不是在寻求调试代码的帮助,但是任何提示都将是有用的!谢谢,这是我的代码:
#include <iostream>
using namespace std;
#include <cstdlib>
#include <ctime>
int main()
{
srand(time(0));
int nCoinTosses = 0;
cout << "How many times would you like to perform the coin toss(Enter 0 to quit)?" << endl;
cin >> nCoinTosses;
cin.ignore(1000, 10);
int i = 0; //counter
while (true)
{
while (true)
{
if (nCoinTosses == 0) break;
int choice = rand() % 2;
if (nCoinTosses == 0) break;
if (choice == 0)
cout << "Heads" << endl;
if (choice == 1)
cout << "Tails" << endl;
i++;
if (i == nCoinTosses) break;
}//while
}//while
}
答案 0 :(得分:2)
您可以使用可能更具可读性的for循环编写它。这是一个例子
#include <iostream>
using namespace std;
int main()
{
srand(time(NULL));
int nCoinTosses = 0;
cout << "How many times would you like to perform the "
" coin toss(Enter 0 to quit)?"
<< endl;
cin >> nCoinTosses;
for (int i = nCoinTosses; i > 0; i--)
{
if (rand() % 2)
cout << "Heads" << endl;
else
cout << "Tails" << endl;
}
}
答案 1 :(得分:2)
真的取决于您要通过这些循环实现的目标。目前,它永远不会脱离您的第一个无限循环。这是故意的吗?
您希望程序如何执行? 每次迭代之后,您是否应该询问用户是否要再次运行?
我会做这样的事情
int main()
{
srand(time(NULL));
int nCoinTOsses = 0;
do {
cout << "How many..."
cin >> nCoinTosses;
cin.ignore();
for( int i = 0; i < nCoinTosses; ++i )
{
if( rand % 2 == 0 )
{
cout << "Heads";
}
else
{
cout << "Tails";
}
}
} while( nCoinTosses != 0 );
}
更改的理由:减少变量的数量,无需在这里和那里使用中断。拥有两个while(true)语句和breaks只会使代码更难以阅读和理解。
我要说的是集中精力使代码更具可读性,然后着眼于使代码更高效。通过在此处和此处添加随机中断以及两个while循环(这没什么错),它们本身并没有真正的意义,从而为代码增加了不必要的复杂性。
while( nCoinTosses != 0 )
和for( int i = 0; i <nCoinTosses)
为循环的作用提供了更多的上下文。不必寻找休息和条件。