c++怎么判断20道选择题的对错?
高洛峰
高洛峰 2017-04-17 14:52:10
0
1
797

write a program to grade a multiple-choice exam. The exam has 20 questions, each answered with a letter in the range of ‘a’ through ‘f’.
The program should read the key from input, then read each answer and output the ID number and score. Erroneous input should result in a error message.
Input
The first line of input is the key, consisting of a string of 20 characters.
The remaining lines are exam answers, each of which consists of a student ID number, a space, and a string of characters.
The input ends with 0.
Output
Output the score for each ID number in a sigle line, consisting the ID number, a space, and the score or error message.
Sample Input
Copy sample input to clipboard
abcdefabcdefabcdefab
1234567 abcdefabcdefabcdefab
9876543 abddefbbbdefcbcdefac
5554446 abcdefabcdefabcdef
4445556 abcdefabcdefabcdefabcd
3332221 abcdefghijklmnopqrst
0
Sample Output
1234567 20
9876543 15
5554446 Too few answers
4445556 Too many answers
3332221 Invalid answers

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回覆(1)
洪涛
#include <iostream>
#include <vector>
#include <string>
using namespace std;

bool isAnswerValid(string ans)
{
    if(ans.length()<20) {
        cout << " Too few answers" << endl;
        return false;
    }
    else if(ans.length() > 20) {
        cout << " Too many answers" << endl;
        return false;
    }

    for(auto i=ans.begin(); i!=ans.end(); i++)
        if( (char)*i<'a' || (char)*i>'f') {
            cout << " Invalid answers" << endl;
            return false;
        }

    return true;
}

int howManyRightAnswer(string ans, string stu)
{
    int val = 0;

    if(isAnswerValid(stu)==true) {
        auto i = ans.begin();
        auto j = stu.begin();

        while(i!=ans.end()) {
            if( *i == *j)
                val++;
            i++;
            j++;
        }
        return val;
    }
    else
        return  -1;
    
}

int main(void) 
{
    string ans, stu;
    int sid, rignum;
    cin >> ans;
    if (isAnswerValid(ans)==true) {
        scanf("%d", &sid);
        while(sid!=0) {
            cin >> stu;
            cout << sid;
            rignum = howManyRightAnswer(ans,stu);
            if(rignum!=-1)
                printf(" %d\n", rignum);
            scanf("%d", &sid);
        }
    }

}

VC++2010 測試沒問題。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板