For循环只运行一次c ++

时间:2016-03-15 20:40:29

标签: c++ loops

嗨我试图运行类似于掷硬币的醉步行问题。我编写了代码,但它只进入一次for循环,而不是像我想要的那样进入1,000,000次。我不知道自己做错了什么,所以我希望你们都能指出我正确的方向,谢谢。

  cout << "enter the starting position.\n";
  cin >> i;
  cout << "At starting block " << i << endl;

  for(j = 1; j < 1000000; j++)
  {

     while(i < 8 && i > 1)
     {
        x = rand() % 3;
        if(x == 0)
        {
           i++;
           tot_mov++;
        }
        else
        {
           i--;
           tot_mov++;
        }
     }

    if(i == 1)
    {
       tot_pub++;
    }

    if(i == 8)
    {
       tot_hom++;
    }

  }

    avg_mov = tot_mov / 1000000;
    avg_pub = tot_pub / 1000000;
    avg_hom = tot_hom / 1000000;

    cout << "Total moves " << tot_mov << endl;
    cout << "Average moves " << avg_mov << endl;
    cout << "Total Home " << tot_hom << endl;
    cout << "Average home " << avg_hom << endl;
    cout << "Total pub " << tot_pub << endl;
    cout << "Average pub " << avg_pub << endl;

    return;

1 个答案:

答案 0 :(得分:1)

@MattJordan在评论中说,这个问题是你在循环过程中没有重置i,并且不使用临时变量。循环本身运行了1,000,000次,只有i不再符合while循环条件时,

(此外,由于您将j初始化为1而非0,因此仅循环了999,999次。)

试试这个:

cout << "enter the starting position.\n";
cin >> i;
cout << "At starting block " << i << endl;

for(int j = 0; j < 1000000; j++)
{
    int i_temp = i;

    while(i_temp < 8 && i_temp > 1)
    {
        x = rand() % 3;
        if(x == 0)
        {
            i_temp++;
            tot_mov++;
        }
        else
        {
            i_temp--;
            tot_mov++;
        }
    }

    if(i_temp == 1)
    {
        tot_pub++;
    }

    if(i_temp == 8)
    {
        tot_hom++;
    }

}

// Casts are optional, they're there to prevent
//  any integer truncation before value is saved to
//  the double.
avg_mov = static_cast<double>(tot_mov) / 1000000;
avg_pub = static_cast<double>(tot_pub) / 1000000;
avg_hom = static_cast<double>(tot_hom) / 1000000;

cout << "Total moves " << tot_mov << endl;
cout << "Average moves " << avg_mov << endl;
cout << "Total Home " << tot_hom << endl;
cout << "Average home " << avg_hom << endl;
cout << "Total pub " << tot_pub << endl;
cout << "Average pub " << avg_pub << endl;

return;

Working example