Search code examples
c++debuggingrandom-walksetw

Beginner C++ - Simple random walk program with a strange setw bug


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.sstatic.net/USx4U.png Thanks for any help y'all can give!


Solution

  • 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.