2012-02-21 20 views
0

私は、スタックのために2D配列を使ってリンクリストをシミュレートすると思われるプロジェクトに取り組んでいます。私はコードを持っていますが、乱数の働きを理解することはできません。私はオンラインで見ましたが、オンラインでは、ランダム関数をシミュレーションでどのように動作させるか説明していません。ここでは以下の私のコードは次のとおりです。C++スタックと2D配列

`#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)); 

そして、別のノートに

、私はC++ヘッダーには、これらのよう ctimecstdlibをしている使用して好みます。また、最新のコンパイラにアクセスできる場合は、 randomヘッダーを参照してください。ここで

0

はC++

#include <cstdlib> 
#include <ctime> 

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

ああ[OK]を、私は見に乱数を使用する方法です。ありがとうございました。私はそのランダム関数を初期化する必要がありました。皆さんありがとう – NerdPC