简体   繁体   English

初学者C ++-带有奇怪setw错误的简单随机游走程序

[英]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. 我的任务是为C ++类创建一个非常简单的随机游走程序。 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. 即使坐标显示其从左到右交替走动,步长也会从0到10排列。

#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! http://i.stack.imgur.com/USx4U.png谢谢大家的帮助!

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. 当pos-10小于0时,则您打印此值的区域会更长(由于减号),因此您的“行者”会在输出中右移一个位置。

Similar reason when it goes from 9 to 10 it isn't right. 类似的原因,当它从9变为10时,它是不正确的。

Think about what it means that the colons on the left are not in a straight line. 考虑一下左边的冒号不是直线的意思。

The "lining up" for i between 1 and 10 makes sense. i在1到10之间的“排队”是有道理的。

Take the first two lines, for example: 以前两行为例:

  • When i == 1 , you have pos == 10 , and the * is printed 10 spaces after the : . i == 1 ,您的pos == 10 ,并且*:之后10个空格打印。
  • When i == 2 , you have pos == 9 , and the * is printed 9 spaces after the : . i == 2 ,您有pos == 9 ,并且*:之后打印9个空格。

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. 但是,因为您在第一行中打印0 (一个字符),在第二行中打印-1 (两个字符),所以*结束于每行的同一位置。

BTW, you are using the same value (13699) for seeding the RNG every time you run your program. 顺便说一句,您每次运行程序时都使用相同的值(13699)作为RNG的种子。

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. 您需要在源文件中#include <time.h>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM