gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:53:44 25 4
gpt4 key购买 nike

我的任务是为 C++ 类创建一个非常简单的随机游走程序。我写了它并且相当确定一切都是正确的但是我遇到了这个奇怪的错误。从 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

这里显然存在某种模式,但对于我的生活我无法弄清楚...如果有帮助,这里是输出屏幕截图的链接。 http://i.stack.imgur.com/USx4U.png感谢您提供的任何帮助!

最佳答案

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

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

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

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

关于c++ - 初学者 C++ - 带有奇怪 setw 错误的简单随机游走程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22488691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com