如何比较这两个数组

How do I compare these two arrays?

本文关键字:两个 数组 比较 何比较      更新时间:2023-10-16

基本上,我有两个数组。一个具有测试的正确答案,另一个具有用户对测试的答案。如何比较两者?例如:

如何显示用户在测试中的得分为 15-20?
如何显示用户答错了多少个问题?

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
    const int NUM_ANSWERS = 20;
    char answers[NUM_ANSWERS] = { 'A', 'D', 'B', 'B', 'C', 'B', 'A', 'B', 'C', 'D', 'A', 'C', 'D', 'B', 'D', 'C', 'C', 'A', 'D', 'B' };
    char userAnswer[NUM_ANSWERS];
    string textName;
    int count = 0;
    cout << "nEnter a text file name ";
    cin >> textName;
    ofstream textFileOut;
    textFileOut.open(textName);
    for (int i = 0; i < NUM_ANSWERS; i++)
    {
        cout << "nEnter the test answers ";
        cin >> userAnswer[i];
        textFileOut << userAnswer[i] << 'n';
    }
    textFileOut.close();
    ifstream textFileIn;
    textFileIn.open(textName);
    while (count < NUM_ANSWERS && textFileIn >> userAnswer[count])
        count++;
    textFileIn.close();
    cout << endl << endl;
    system("pause");
    return(0);
}

一个简单的循环应该为你解决这个问题。通过使用计数器,您可以获得正确答案的数量,如果所有答案的价值相同,则可以同时获得正确答案的数量和用户分数。

numCorrect = 0;
for (int i = 0; i < count; i++)
{
    if (userAnswer[i] == answers[i])
        numCorrect++;
}