1
我想要求用戶設置一個指南針的方向爲char,使用n代表北,e代表東等等,或者使用默認值設置爲北。例如(0,0,'n')。在課堂上隨機使用一個循環
然後我想讓它在任何方向隨機移動100次。 我現在困惑於我班內的循環。我不知道我應該在哪裏添加循環。另外,輸出顯示我輸入的值。
我將不勝感激您的幫助!
輸出例如:
0 === 0 ---ñ
#include<iostream>
#include<string>
#include<iomanip>
#include<ctime>
using namespace std;
class bug
{
public:
bug();
bug(int x_pos, int y_pos, char direction);
void turn(char direction);
void move(int x, int y,char direction);
int get_X() const;
int get_Y() const;
char get_direction() const;
private:
int x;
int y;
char direction;
};
bug::bug(int x_pos, int y_pos, char d)
{
x = x_pos;
y = y_pos;
direction = d;
}
bug::bug()
{
x = 0;
y = 0;
direction = 'n';
}
void bug::turn(char direction)
{
int num = 1 + rand() % 3;
if (direction == 'n')
{
if (num == 1)
direction = 'e';
else if (num == 2)
direction = 'w';
else if (num == 3)
direction = 'n';
}
else if (direction == 'w')
{
if (num == 1)
direction = 'w';
else if (num == 2)
direction = 'n';
else if (num == 3)
direction = 's';
}
else if (direction == 's')
{
if (num == 1)
direction = 's';
else if (num == 2)
direction = 'w';
else if (num == 3)
direction = 'e';
}
else if (direction == 'e')
{
if (num == 1)
direction = 'e';
else if (num == 2)
direction = 'n';
else if (num == 3)
direction = 's';
}
}
void bug::move(int x, int y, char direction)
{
if (direction == 'n')
y = y + 1;
else if (direction == 'w')
x = x - 1;
else if (direction == 's')
y = y - 1;
else if (direction == 'e')
x = x + 1;
}
int bug::get_X() const
{
return x;
}
int bug::get_Y() const
{
return y;
}
char bug::get_direction() const
{
return direction;
}
void display(bug start)
{
cout << start.get_X()<<"==="<<start.get_Y() << "---"<<start.get_direction() << endl;
}
int main()
{
srand(time(0));
bug first;
int choice;
cout << custom mode(1) or default mode(2) ? ";
cin >> choice;
if (choice == 1)
{
int x, y;
char dir;
cout << "the x axis: ";
cin >> x;
cout << "the y axis: ";
cin >> y;
cout << "the direction: ";
cin >> dir;
bug first(x, y, dir);
//first.turn(dir);
//first.move(x,y);
display(first);
}
else
{
for(int j =0;j<100;j++)
{
bug first;
//first.turn;
//first.move();
//for(int j =0;j<100;j++)
display(first);
}
}
system("pause");
}
沒有輸入檢查的東西,如輸入模式或其他東西,而不是南,北,西,或東小寫字母以外的東西。這是暫時的,直到100個隨機移動循環的位置被確定爲止? –
只有當用戶選擇2(默認模式)時,或者在任何情況下,您是否希望該錯誤進行隨機遊走?你知道如何隨意選擇一個方向嗎?你想讓步行成爲一個成員函數,還是你想'main'調用'move' 100次? – Beta
在運動本身上,x和y有上限和下限嗎?例如,這是嚴格的屏幕位置,永遠不會低於'(0,0)',並且永遠不會比'(1440,900)'更高? –