【发布时间】:2019-04-25 14:13:24
【问题描述】:
我不是 C++ 专家,但我正在尽力而为,我有这段代码,我试图让用户输入 1 到 12 之间的数字,无论他们输入什么数字,他们的二维数组都将调整为他们的数字,例如:
- 请输入一个数字:3
- 程序将输出一个大小为 3x3 的二维数组,如果输入“4”,则为 4x4 网格等。
在过去的几天里,我查看了许多示例,但我无法将其全神贯注并将其应用到我的代码中。如果有人可以帮助我,我将不胜感激,这就是我到目前为止所做的:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <time.h>
#include <vector>
using namespace std;
double Atemp = 0;
double Utemp = 0;
double Working = 0;
double Total = 0;
char Answer = 'x';
int Umain;
const int ROWS = ?;
const int COLS = ?;
typedef float Table[ROWS][COLS];
void displayOverview ();
void playOrQuit();
void outputSubSquare(Table table, int x, int y);
void fillTableWithRands(Table table);
void outputTable(Table table);
void fillIntArray(int array[], int size);
void reverseArray(int array[], int size);
void outputIntArray(int array[], int n);
int main(){
displayOverview();
playOrQuit();
int maxNum = 4;
int intArray[maxNum];
fillIntArray(intArray, maxNum);
outputIntArray(intArray, maxNum);
srand(time(NULL));
Table myTable;
fillTableWithRands(myTable);
outputTable(myTable);
return 0;
}
void displayOverview(){
}
void playOrQuit(){
}
void fillIntArray(int array[], int size){
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;
for(int i = Atemp; i<0;i++){
cin >> array[i];
}
}
}
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] = rand()%4+ 1;
}
}
}
void outputTable(Table table){
for(int i = 0; i<ROWS; i++){
for (int j = 0; j<COLS; j++){
cout << table[i][j] << " ";
}
cout << endl;
}
}
void outputIntArray(int array[], int n){
for(int i = 0; i<n; i++){
printf("%d", array[i]);
}
cout << endl;
}
【问题讨论】:
-
std::vector<std::vector<int>> grid(rows, std::vector<int>(cols));最大的问题——你可以使用std::vector吗?如果不是try this -
如果
vector不被允许,我可以建议自己围绕一个动态分配的数组创建一个简单的 Matrix 类吗?很好的例子:isocpp.org/wiki/faq/operator-overloading#matrix-subscript-op