2013-06-01 91 views
1

美好的一天。我的代碼中發生了一件相當奇怪的事情。我想創建一個隨機數字輸入到我的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(); 
} 

請您能有所幫助。

謝謝。

+2

- 你想我== quest_position [0]。 像這樣,你正在'重新初始化'我。 –

+0

_「rand()%9 + 0;」_ - 「0」的原因是什麼? – soon

回答

1
if(i = quest_position[0] && j == quest_position[1]) 
     cout << quest; 

應該是:

if(i == quest_position[0] && j == quest_position[1]) 
    //^^^Error here should be logical equal 
     cout << quest; 

您可能會發現現場演示在這裏:Code Demo

同時,你應該使用標題:

#include <ctime> 

,並刪除

#include <stdlib.h> 

因爲您已經包含<cstdlib>

+0

謝謝,我確實看到了這個(和固定的),但是一旦插入了任務,它會給我一個到多個x的網格。 – Rijnhardt

+0

@Rijnhardt如果它沒有給你期望的話,你可能需要檢查你的代碼的邏輯輸出? – taocp

+0

@Toacp是我的if語句相互衝突嗎? – Rijnhardt

1

您在線路錯過==

if(i == quest_position[0] && j == quest_position[1]) 
1

嘗試這種情況:

if(i = quest_position[1] && j == quest_position[1])

如果(ⅰ= quest_position [0] &&Ĵ== quest_position [1])<
相關問題