My code works so far but I have a logic error in the 17th to 30th line of code and I can't seem to figure it out. I feel like I have too much going on.
The prompt for the problem is as follows:
Two two-dimensional arrays m1
and m2
are identical if they have the same contents. Write a function that returns true if m1
and m2
are identical, using the following header:
const int SIZE = 3;
bool equals(const int m1[][SIZE], const int m2[][SIZE]);
Write a test program that prompts the user to enter two 3 x3 arrays of integers and displays whether the two are identical. Here are the sample runs (below).
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
This is my code (sorry if it is bad and messy im still learning)
#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;
}
Thank You
Aucun commentaire:
Enregistrer un commentaire