c++抛硬币式嵌套循环
Nested loops with C++ coin toss
我必须写一个程序来运行抛硬币的循环。我可以在控制台上输入一个数字,然后让它循环多次抛硬币。我需要使用嵌套循环。我已经花了好几个小时研究这个问题,但还是没能成功。
控制台i/o应该如下所示:
输入要执行的投掷次数[0=exit]: 3头尾巴头
输入要执行的投掷次数[0=exit]: 2尾巴尾巴
输入要执行的投掷次数[0=exit]: 0
这是我到目前为止的代码:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main ()
{
srand(time(0));rand();
int result = rand() % 2;
while (true)
{
int n; // this many tosses
cout << "How many tosses";
cin >> n;
cin.ignore (1000, 10);
if (n == 0)
break;
for (int i = 0; i < n; i++)
//random number generator
{
if (result == 0)
cout<< "Heads"<<endl;
else if (result == 1)
cout << "Tails"<<endl;
else if (result != 0 || result !=1)
return 0;
} //for
}//while
}//main
您的for
循环没有您实际上试图在{}
内部执行的部分。尝试在你想循环的部分周围添加大括号,看看是否可以为你修复它。
我编辑了代码中的缩进,以向您展示唯一将实际循环的行(srand(time(0))
)
-
您需要在循环块周围加上括号,即
for( int i = 0; i < n; i++ ) { // Code goes here }
如上所示,您需要初始化 将
rand()
的播种置于while(...)
循环之前。
i
。
您需要将int result = rand() % 2;
移动到for
循环中!否则,每次都将得到相同的结果,直到重新启动应用程序。
for (int i = 0; i < n; i++)
//random number generator
{
int result = rand() % 2;
if (result == 0)
cout<< "Heads"<<endl; /* to make your output look like your example you should removed the <<endl from here */
else if (result == 1)
cout << "Tails"<<endl; /* and here */
else if (result != 0 || result !=1)
return 0;
} //for
/* and put it here */
cout << endl;
相关文章:
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 了解嵌套循环打印星号图案
- 无法掌握嵌套循环的写作技巧
- 在 c++ 中实现嵌套循环的更短方法吗?
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 毕达哥拉斯三重嵌套循环误解
- T(n) 表示嵌套循环
- 2 个嵌套循环的时间复杂度
- 嵌套循环背后的逻辑
- 使用 %s C++嵌套循环
- 嵌套循环和重复迭代器
- 如何在 c++ 下使用嵌套循环和正则表达式降低时间复杂度?
- C++在乘法图中放置随机值(嵌套循环)
- 如何使用 OpenMP 减少嵌套循环?
- 为什么使用 2 个嵌套循环 O(n^2) 复杂度来解决二和问题,当只改变循环计数器逻辑时运行得更快?
- 学习嵌套循环C++与示例混淆
- 如何在CUDA中嵌套循环
- std::vector上的嵌套循环
- 具有动态数组分配的OpenMP嵌套循环
- c++抛硬币式嵌套循环