2012-02-21 52 views
0

我一直在做一個項目,假設通過使用二維數組來模擬鏈接列表。我有代碼,但我無法弄清楚如何使隨機數字的工作。我在網上查看過,但在線並未解釋如何使隨機功能與仿真一起工作。這裏是我下面的代碼:C++堆棧和二維數組

`#include <iostream> 

#include <stdlib.h> 
using namespace std; 

int myTop = -1; 
int index = -1; 
int next = -1; 
int tt[25][2]; 
void construct() 
{ 
    tt[25][2]; 
} 

void empty() 
{ 
    if (myTop == -1) 
     cout << "Empty Stack"; 
    else 
     cout << "Full Stack"; 
} 

void push(int x) 
{ 
    if (myTop < 24) 
    { 
     myTop++; 
     tt[myTop] = x; 
    } 
    else 
     cout << "The stack is full.";  
} 

void top() 
{ 
    if (myTop != -1) 
     cout << "Top Value is: " << tt[myTop]; 
    else 
     cout << "Empty Stack"; 

} 

int pop() 
{ 
    int x; 
     if(myTop<=0) 
     { 
       cout<<"stack is empty"<<endl; 
       return 0; 
     } 
     else 
     { 
       x=tt[myTop]; 
       myTop--; 
      } 
      return(x); 

} 

void display() 
{ 
    for (int row=0; row<25; row++) 
    { 
     for (int column=0; column<3; column++) 
     { 
      cout << tt[row][column] << "\t"; 
      if (column == 2) 
       cout << endl; 
     } 
    } 
    cout << endl; 
} 

int main() 
{ 
    push(rand() % 25); 
    display(); 
    push(rand() % 25); 
    display(); 
    push(rand() % 25); 
    display(); 
    push(rand() % 25); 
    display(); 
    top(); 
    pop(); 
    display(); 
    top(); 
    pop(); 
    display(); 
    top(); 
    pop(); 
    display(); 
    } 

回答

4

您haven`t初始化隨機數發生器(這被稱爲 「種子」) 。

將下列內容添加到您的代碼中。

#include <time.h> 

srand (time(0)); 

而在另一方面,我更喜歡使用ctimecstdlib那些是C++頭(雖然這是可以討論)。另外,如果您有權訪問最新的編譯器,請查看random標題。

0

這裏是如何用C使用隨機數++

#include <cstdlib> 
#include <ctime> 

int main() 
{ 
    srand(time(NULL)); 
    number = rand() % 10 + 1; # Random number between 1 and 10 
} 
+0

那好吧我明白了。謝謝。我只需要初始化那個隨機函數。感謝你們所有人 – NerdPC 2012-02-21 05:32:54