【问题标题】:C++ stacks and 2D arrayC++ 堆栈和二维数组
【发布时间】:2012-03-11 11:05:44
【问题描述】:

我一直在研究一个项目,该项目假设通过使用二维数组作为堆栈来模拟链接列表。我有代码,但我不知道如何使随机数起作用。我在网上看过,但网上没有解释如何使随机函数与模拟一起工作。下面是我的代码:

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

【问题讨论】:

    标签: c++ arrays stack multidimensional-array


    【解决方案1】:

    您尚未初始化随机数生成器(这称为“播种”)。

    将以下内容添加到您的代码中。

    #include <time.h>
    
    srand (time(0));
    

    另一方面,我更喜欢使用ctimecstdlib,因为它们是c++ 头文件(尽管这可以讨论)。此外,如果您可以访问最新的编译器,请查看 random 标头。

    【讨论】:

      【解决方案2】:
      【解决方案3】:

      这里是如何在 C++ 中使用随机数

      #include <cstdlib>
      #include <ctime>
      
      int main ()
      {
        srand(time(NULL));
        number = rand() % 10 + 1; # Random number between 1 and 10
      }
      

      【讨论】:

      • 哦,好的,我明白了。谢谢你。我只需要初始化那个随机函数。谢谢大家
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多