美好的一天。我的代碼中發生了一件相當奇怪的事情。我想創建一個隨機數字輸入到我的quest_postition數組中以在我的網格數組中使用它。我希望每次運行程序時位置都不一樣。給一個數組一個隨機數
它正在做的是進入一個無限循環並一直顯示網格。
這裏是我的代碼:
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <time.h>
using namespace std;
void draw_grid()
{
char grid[9][9] = { {'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'}};
char character = '*';
char quest = 'Q';
int position[2] = {4,4};
int quest_position[2];
srand(time(NULL));
quest_position[0] = rand() % 9 + 0;
quest_position[1] = rand() % 9 + 0;
char direction;
for(int i = 0; i < 9; i++){
for (int j = 0; j < 9; j++){
if(i == position[0] && j == position[1])
cout << character;
if(i = quest_position[0] && j == quest_position[1])
cout << quest;
else
cout << grid[i][j];
cout << " ";
}
cout << endl;
}
}
int main()
{
draw_grid();
}
請您能有所幫助。
謝謝。
- 你想我== quest_position [0]。 像這樣,你正在'重新初始化'我。 –
_「rand()%9 + 0;」_ - 「0」的原因是什麼? – soon