将两个数组中的差异记录在第三个数组中

Take differences in two arrays and record their number in a third array

本文关键字:数组 记录 三个 两个      更新时间:2023-10-16

所以我一直在努力解决这个问题。我的所有代码目前都能工作,除了我的最后一个模块,我试图比较两个数组的差异,并将问题编号记录到一个新的数组中。我真的不知道该怎么设置。任何帮助都将不胜感激。

主要问题是我创建的数组不正确。我不知道如何设置一个随着输入值而变大的空白数组。除非我真的把这个概念搞砸了。当我尝试不同的事情时,我已经对当前的问题进行了评论。

#include <iostream>
using namespace std;
const int COLS = 20;
void input_data(char [], int);
void compare_data(char [], int, char [], int);
int main()
{
char letters[COLS];
char answers[] = { 'A', 'D', 'B', 'B',
'C', 'B', 'A', 'B',
'C', 'D', 'A', 'C',
'D', 'B', 'D', 'C',
'C', 'A', 'D', 'B'};
input_data(letters, COLS);
compare_data(letters, COLS, answers, COLS);
}
void input_data(char letter[], int size)
{
cout << "Please enter the student's answers for each of the questions. n";
cout << "Press Enter after typing each answer. n";
cout << "Please enter only an A, B, C, or D for each question. n";
for (int i = 1; i <= size; i++)
{
cout << "Question " << i << ": ";
cin >> letter[i - 1];
while (letter[i - 1] != 'A' && 
letter[i - 1] != 'B' &&
letter[i - 1] != 'C' &&
letter[i - 1] != 'D')
{
cout << "Please enter only A, B, C, or D n";
cout << "Question " << i << ":";
cin >> letter[i - 1];
}
}
}
void compare_data(char letter[], int size, char answer[], int cols)
{
int ans_correct = 0;
int ans_wrong = 0;
//int incorrect[20];
for (int i = 1; i <= size; i++)
{
if (letter[i] == answer[i])
ans_correct += 1;
else
{
ans_wrong += 1;
//incorrect[i-1] = i;
}
}
if (ans_correct >= 15)
cout << "The student passed the exam. n";
else
cout << "The student did not pass the exam. n";
cout << "Correct Answers: " << ans_correct << endl;
cout << "Incorrect Answers: " << ans_wrong << endl << endl;
cout << "Questions that were answered incorrectly: n";
for (int i = 1; i < size; i++)
{
//cout << incorrect[i-1] << endl;
}
}

好的,这是一个工作版本。它不会增长不正确的数组,因为对于这样一个小的操作来说,这将是过度的,而且您无论如何都在使用常量"COLS"。

既然这是一个带有c++标记的问题,如果你真的想要一个动态数组,为什么不使用std::vector呢?可以使用C样式数组执行类似的操作,但这非常混乱。

void compare_data(char letter[], int size, char answer[], int cols)
{
int ans_correct = 0;
int ans_wrong = 0;
//setup array big enough to hold all answers
//and initialize to 0
int incorrect[COLS] = {0};
// Your original code had wrong loop limits!
for (int i = 0; i < size; i++)
{
if (letter[i] == answer[i])
ans_correct += 1;
else
{
//Fill in incorrect only on wrong answers!
//But the number you want to record is the
//the number of the question, which is i + 1
incorrect[ans_wrong] = i + 1;
ans_wrong += 1;
}
}
if (ans_correct >= COLS/2)
cout << "The student passed the exam. n";
else
cout << "The student did not pass the exam. n";
cout << "Correct Answers: " << ans_correct << endl;
cout << "Incorrect Answers: " << ans_wrong << endl << endl;
cout << "Questions that were answered incorrectly: n";
//Even if the array is bigger, you don't wnat to output the
//unused parts
for (int i = 0; i < ans_wrong; i++)
{
cout << incorrect[i] << endl;
}
}