如何用随机数填充2D数组?

时间:2018-11-21 19:06:02

标签: c++ arrays multidimensional-array

我试图用随机数填充2D数组,但是我得到的是随机大数,而不是1到4之间的随机数

这是我要完成的工作:

  • 当询问用户:输入1到12之间的数字:(用户输入) 5
  • 用户输入5后将获得5x5数组
  • 然后我要用2到1之间的随机数填充2D数组

这是我的代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <iomanip>

using namespace std;

double Atemp = 0;
double Utemp = 0;
double Working = 0;
double Total = 0;
char Answer = 'x';
int Umain;
const int LG_GRID = 12;
const int ROWS = 3;
const int COLS = 3;
const float DIV = 4;

typedef float Table[ROWS][COLS];


void displayOverview ();

void playOrQuit();

void promptNumber();

void outputSubSquare(Table table, int x, int y);
void fillTableWithRands(Table table);
void outputTable(Table table);


int main(){

    displayOverview();

    playOrQuit();

    srand(time(NULL));
    Table myTable;

    fillTableWithRands(myTable);
    outputTable(myTable);



    return 0;
}

void displayOverview(){

}

void playOrQuit(){

    string playOrNot;

    cout << "If you want to play please press 'p' for play, and 'q' if you wish to quit\n";
    cin >> playOrNot;

    if(playOrNot == "p"){
        cout << "Awesome, lets start playing !!! \n";

    }if(playOrNot == "q"){
        cout << "Alright then, see you soon !!\n";
        exit(0);
    }if(playOrNot != "p" && playOrNot != "q"){
        cout << "Invalid entry !!\n";
        exit(0);
    }
}


void promptNumber(){

    do{
      cout << "Please Enter numbers between 1 and 12: ";
      cin >> Umain;
      if(Umain <= 12){
            for (Utemp = Umain; Utemp > 0; Utemp--){
          cout << "Please enter a number between 1 and 4: ";
          cin >> Atemp;
            }
      }else{
    cout << "Not within limit :(\n";
      }
    }while (Answer == 'y');
}

void fillTableWithRands(Table table){

  for(int i = 0; i<ROWS; i++){
    for (int j = 0; j<COLS; j++){
      table[i][j]  = (float)(rand())*DIV;
    }
  }
}

void outputTable(Table table){
  for(int i = 0; i<ROWS; i++){
    for (int j = 0; j<COLS; j++){
      cout << table[i][j] << "\t";
    }
    cout << endl;
  }
}

0 个答案:

没有答案