1

I've been tasked with creating a very simple random walk program for a C++ class. I wrote it and was fairly sure everything was correct but I am getting this strange bug. From 0 to 10 the steps line up even though the coordinates show that its taking alternating left and right steps.

#include<iostream>
#include<iomanip>
#include<cmath>

using namespace std;
int main()
{
   int steps,i,pos=10;
   srand(13699);

   cout << "Please enter the amount of steps to be taken: ";
   cin >> steps;
   cout << endl;
   for (i=0;i<=steps;i++)
   {
       if (rand()%2)
       pos+=1;
   else
       pos-=1;
   cout << i << ": " << pos-10 << ": " << setw(pos) << "*" << endl;
   }
} // main

There is very obviously some sort of pattern here, but for the life of me I can't figure it out... Here is a link to a screenshot of the output if it helps. http://i.stack.imgur.com/USx4U.png Thanks for any help y'all can give!

4

2 回答 2

0

1到10之间的“排队”i是有道理的。

以前两行为例:

  • i == 1, 你有pos == 10, 并且在.*之后打印 10 个空格:
  • 什么时候i == 2,你有pos == 9,并且在.*之后打印 9 个空格:

但是因为您在第一行打印0(一个字符),在第二行打印(-1两个字符),所以*最终在每一行的相同位置。

顺便说一句,每次运行程序时,您都使用相同的值 (13699) 来播种 RNG。

尝试使用更“随机”的值,例如基于时间的值:

srand((unsigned int)time(NULL));

您需要#include <time.h>在源文件中。

于 2014-03-18T19:28:42.270 回答
0

答案不在代码中,而是在您对输出的解释中。

当 pos-10 小于 0 时,您打印此值的区域会更长(因为有减号),然后您的“walker”会在输出中向右移动一个位置。

类似的原因,当它从 9 变为 10 时,它是不正确的。

想想左边的冒号不在一条直线上是什么意思。

于 2014-03-18T19:19:08.207 回答