从用户处取4*4矩阵,检验是否包含2*2子矩阵具有相同的值

  • 本文关键字:包含 用户 矩阵 是否 检验 c++
  • 更新时间 :
  • 英文 :


我只需要用户输入4*4矩阵的字符,根据是否有2 * 2子矩阵有相同的输入,输出将是是或否。代码总是打印false。

代码为:

#include <iostream>
using namespace std;
int main()
{
//input
char color[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cin >> color[i][j];
}
}

//for testing if there are a squar  
// * * * *
// * * # #
// # # * *
// * * # #

// 'yes' as
// * * 
// * *
// is a squar of 2*2
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j != 3) {
if (color[i][j] == color[i][j + 1] == color[i + 1][j] == color[i + 1][j + 1]) {
cout << "yes";
break;
}
else cout << "no";
}
}
}
//for (int i = 0; i < 4; i++) {
//for (int j = 0; j < 4; j++) {
//if (j == 3)
//cout << colors[i][j] <<"n";
//else
//cout << colors[i][j];
//}
//}
return 0;
}

此条件错误:

if (color[i][j] == color[i][j + 1] == color[i + 1][j] == color[i + 1][j + 1]
为简单起见,请考虑
if (a == b == c) 

解析为

if ( (a == b) == c)

比较a==bc的结果。a==b的结果为truefalse,可分别转化为10

当存在一个2x2子矩阵且所有元素都等于1时,您将在屏幕上得到"yes",尽管这可能是错误的原因。

你真正想要的是:

if ( a==b && a==c)

不要忽略编译器的警告!使用正确的标志,代码无法编译:https://godbolt.org/z/45oqcTEna.

而且,循环超出了数组的边界。您可以防止j出界,但是当i == 3然后color[i + 1][j]试图访问不存在的元素时。而不是迭代到<4,然后排除j == 3,让循环只迭代子矩阵左上角的有效索引:

const size_t size = 4;
const size_t sub_matrix_size = 1;
for (size_t i=0; i < size-sub_matrix_size; ++i) {
for (size_t j=0; j < size-sub_matrix_size; ++j) {
//... 

相关内容

最新更新