2012-02-21 51 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