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. https://i.stack.imgur.com/USx4U.png Thanks for any help y'all can give!

stefan
  • 10,215
  • 4
  • 49
  • 90
TimmyG
  • 13
  • 1
  • 4

2 Answers2

0

The answer is not in the code but rather in your interpretation of the output.

When the pos-10 is less than 0 then the area where you print this value is longer (because of the minus sign), then your 'walker' is shifted right a position in the output.

Similar reason when it goes from 9 to 10 it isn't right.

Think about what it means that the colons on the left are not in a straight line.

Elemental
  • 7,365
  • 2
  • 28
  • 33
0

The "lining up" for i between 1 and 10 makes sense.

Take the first two lines, for example:

  • When i == 1, you have pos == 10, and the * is printed 10 spaces after the :.
  • When i == 2, you have pos == 9, and the * is printed 9 spaces after the :.

But because you are printing 0 (one character) in the first line and -1 (two characters) in the second line, the * end up on the same place in each line.

BTW, you are using the same value (13699) for seeding the RNG every time you run your program.

Try using a more "random" value, for example, a time-based one:

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

You'll need to #include <time.h> in your source file.

barak manos
  • 29,648
  • 10
  • 62
  • 114
  • Yep this is exactly what was wrong, thanks! And the seed is predefined so that my instructor can check my work. – TimmyG Mar 19 '14 at 20:09