如何将网格的行和列与用户输入进行比较?

时间:2018-11-26 20:36:49

标签: c++ arrays multidimensional-array

好吧,所以我有这段代码,该代码基本上会提示用户输入数字,然后根据用户输入的数字,系统会询问他们(请输入1到4之间的数字)*用户选择的数字。然后,将比较他们的输入以查看网格中是否有任何匹配项(行和列)。让我给你看一个例子:

  • 请输入一个数字: 3
  • 请输入1到4之间的数字: 2
  • 请输入1到4之间的数字: 1
  • 请输入1到4之间的数字: 2

这是您的网格: (3x3网格填充,因为用户输入了 3 ,并填充了随机数字)

 4  2  4
 3  1  1
 4  3  3

这是我的代码示例:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <time.h>
#include <ctime>

using namespace std;

double Atemp = 0;
double Utemp = 0;
double Working = 0;
double Total = 0;
char Answer = 'x';

int Umain;


void printGrid(int &Umain);

void fillIntArray(int array[], int size);
void reverseArray(int array[], int size);
void outputIntArray(int array[], int n);

void compareGrid(int &Atemp);

int main(){


    int maxNum = 2;
    int intArray[maxNum];


    cout << "Please Enter numbers between 1 and 12: ";
    cin >> Umain;


    do{
       if(Umain <=12){
        fillIntArray(intArray, maxNum);
        //outputIntArray(intArray, maxNum);
        printGrid(Umain);
       }
    }while (Answer == 'y');


    return 0;
}


void fillIntArray(int array[], int size){

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


void printGrid(int &Umain){

  cout<<endl;
    cout<<" ";
        int i=1,j;
        for(j = 0; j <= 4*Umain; j++){
            if(j%4==2){
                cout<<" ";
            }
        }

  cout<<endl;
    for(i = 0; i <= 2*Umain; i++){
        for(j = 0; j <= 2*Umain; j++){
        if(i%2==0){
        if(j==0){
            cout<<" ";
        }
        if(j%2==0){
            cout<<" ";
        }else{
            cout<<"---";
        }
      }else{
        if(j%2==0){
            cout<<" | ";
        }else cout<< (rand()%4+1);
      }
    }
        if(i%2!=0){
            cout<<" ";
        }
    cout<<endl;
  }
  cout<<" ";

    for(j = 0, i = 1; j <= 4*Umain; j++){
        if(j%4==2){
            cout<< " ";
        }
  }
  cout<<endl;
}

void compareGrid(int &Atemp){

}

1 个答案:

答案 0 :(得分:0)

一方面,可变大小数组不是C ++的一部分。这部分是错误的:

int maxNum = 2;
int intArray[maxNum];

通过添加constexpr来解决:

constexpr int maxNum = 2;
int intArray[maxNum];

第二,通常这部分没有意义,最后的分号确实令人怀疑:

for (int i = Atemp; i < Atemp; i++); // why?

并假设您已将用户输入收集在大小为3的名为Attempts的数组中,并且intArray是大小为3x3的矩阵,则可以按以下方法将尝试与尝试输入的行/列进行比较所谓的2D数组:

bool Contains() {
    for (size_t iCol = 0; iCol != 3; ++iCol) {
        for (size_t iRow = 0; iRow != 3; ++iRow) {
            if(intArray[iCol][iRow] != Attempts[iRow]) {
                return false;
            }
        }
    }
    return true;
}

更改iColiRow的位置以检查行或列