所以我一直很难解决这个问题。我的所有代码当前都可以正常工作,除了最后一个模块,在该模块中,我试图比较两个数组的差异并将问题编号记录到一个新数组中。我不太确定该如何设置。任何帮助将不胜感激。
主要问题是我创建的数组不正确。我不知道如何设置一个空白数组,该数组在输入值时会变大。除非我真的把这个概念搞砸了。在尝试其他事情时,我当前已将问题注释掉。
#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;
}
}
答案 0 :(得分:0)
好的,这是有效的版本。它不会增长不正确的数组,因为对于这么小的操作而言,这是过大的选择,而且无论如何您都在使用常量'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;
}
}