【发布时间】:2016-04-03 06:16:36
【问题描述】:
到目前为止,我的代码工作正常,但我在第 17 到第 30 行代码中有一个逻辑错误,我似乎无法弄清楚。我觉得我有太多事情要做。
问题提示如下:
如果两个二维数组m1 和m2 具有相同的内容,则它们是相同的。如果 m1 和 m2 相同,则使用以下标头编写一个返回 true 的函数:
const int SIZE = 3;
bool equals(const int m1[][SIZE], const int m2[][SIZE]);
编写一个测试程序,提示用户输入两个 3 x3 整数数组,并显示两者是否相同。以下是运行示例(如下)。
Enter m1: 51 25 22 6 1 4 24 54 6
Enter m2: 52 22 25 6 1 4 24 54 6
output : Two arrays are identical
Enter m1: 51 5 22 6 1 4 24 54 6
Enter m2: 51 22 25 6 1 4 24 54 6
output: Two arrays are not identical
这是我的代码(对不起,如果它很糟糕,我还在学习中)
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
const int SIZE = 3;
bool equals(const int m1[][SIZE], const int m2[][SIZE]) {
bool choice = true;
while (choice) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (m1[i][j] != m2[i][j]) { // code is fine until here. There is a logic error somewhere. m1: 123456789 m2: 987654321 output: array not identical
for (int k = 0; k < SIZE; k++) {
for (int h = 0; h < SIZE; h++) {
if (m1[i][j] == m2[k][h]) {
return true;
}
else {
choice = false;
return false;
}
}
}
}
else {
return true;
}
}
}
}
}
int main() {
string input1, input2, num1, num2;
int count1 = 0, count2 = 0;
int a = 0, b = 0, c = 0;
int a2 = 0, b2 = 0, c2 = 0;
int arr1[SIZE][SIZE];
int arr2[SIZE][SIZE];
cout << "Enter m1: ";
getline(cin, input1);
stringstream line1(input1);
cout << "Enter m2: ";
getline(cin, input2);
stringstream line2(input2);
while (line1 >> num1) {
if (count1 < 3) {
stringstream(num1) >> arr1[0][a];
a++;
}
else if (count1 >= 3 && count1 <= 5) {
stringstream(num1) >> arr1[1][b];
b++;
}
else {
stringstream(num1) >> arr1[2][c];
c++;
}
count1++;
}
while (line2 >> num2) {
if (count2 < 3) {
stringstream(num2) >> arr2[0][a2];
a2++;
}
else if (count2 >= 3 && count2 <= 5) {
stringstream(num2) >> arr2[1][b2];
b2++;
}
else {
stringstream(num2) >> arr2[2][c2];
c2++;
}
count2++;
}
bool answer = equals(arr1, arr2);
if (answer) {
cout << "Two arrays are identical" << endl;
}
else {
cout << "Two arrays are not identical" << endl;
}
system("Pause");
return 0;
}
谢谢
【问题讨论】:
-
肯定只需要一个的差异就可以返回false吗?
-
你为什么使用
while?为什么你有这么多嵌套的fors?如果要比较二维数组,请将其视为具有行和列的表。您必须遍历行并在每一行中遍历列。这意味着,只需要 2 个嵌套的fors -
既然你有一个简单数据类型的静态分配和连续数组,考虑使用
memcmp。 en.cppreference.com/w/cpp/string/byte/memcmp
标签: c++ c++11 multidimensional-array