c++抛硬币式嵌套循环

Nested loops with C++ coin toss

本文关键字:嵌套循环 硬币 c++      更新时间:2023-10-16

我必须写一个程序来运行抛硬币的循环。我可以在控制台上输入一个数字,然后让它循环多次抛硬币。我需要使用嵌套循环。我已经花了好几个小时研究这个问题,但还是没能成功。

控制台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)))

  1. 您需要在循环块周围加上括号,即

    for( int i = 0; i < n; i++ )
    {
        // Code goes here
    }
    
  2. 如上所示,您需要初始化i
  3. rand()的播种置于while(...)循环之前。

您需要将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;