奇怪的错误。在循环中使用rand()和数组

时间:2015-11-27 17:33:09

标签: c++ arrays for-loop random error-handling

我真的无法解释我的程序发生了什么。我真的无法发现可能导致问题的原因。它出现在这个函数中

void test()
{
    srand(time(NULL));

    questionNo = 1;

    for (testLoop = 0; testLoop < 10; ++testLoop)
    {
        const char opArray[3] = { 'x', '+', '-' };
        int pickValue = rand() % 3;
        char Operator = opArray[pickValue];

        int n1 = rand() % 20 + 1;
        int n2 = rand() % 20 + 1;

        if (Operator = '+')
            answer = n1 + n2;
        else if (Operator = '-')
            answer = n1 - n2;
        else
            answer = n1 * n2;

        cout << "Question " << questionNo << "\n";
        ++questionNo;
        cout << n1 + " " << Operator + " " << n2 << "?";
        userAnswer = cin.get();

        if (userAnswer = answer)
        {
            cout << "\n\n Correct!\n";
            system("cls");
            ++score;
        }
        else
        {
        cout << "\n\n Incorrect!\n";
        system("cls");
        }
        Sleep(500);
    }
    cout << "You scored " << score << " out of 10!";
    fileWrite(score);
}

发生的事情的一个例子如下。 这输出到控制台

问题1 @ OY×╝׳×0ƒ11?

甚至是什么??? 它每次都会跳过两个问题。例如,它

“问题1”
“问题3”
“问题5”

2 个答案:

答案 0 :(得分:1)

您在此代码段中使用了分配运算符=而不是比较运算符==

    if (Operator = '+')
        answer = n1 + n2;
    else if (Operator = '-')
        answer = n1 - n2;
    else
        answer = n1 * n2;

按照以下方式进行修改

    if (Operator == '+')
        answer = n1 + n2;
    else if (Operator == '-')
        answer = n1 - n2;
    else
        answer = n1 * n2;

此声明中存在相同的错误

   if (userAnswer = answer)

也代替

   userAnswer = cin.get();

使用operator >>

sin >> userAnswer;

本声明中还有一个拼写错误

    cout << n1 + " " << Operator + " " << n2 << "?";

应该有

    cout << n1 << " " << Operator << " " << n2 << "?";

答案 1 :(得分:1)

你有:

cout << n1 + " " << Operator + " " << n2 << "?";

您应该同时使用<<代替+

cout << n1 << " " << Operator << " " << n2 << "?";

n1 + " "字词是将n1的值添加到存储一空字符串的地址,生成char *,然后<<正在打印它在该字符串结尾之后发现的任何垃圾(假设n1为正且大于1,或者如果它为负则在字符串之前找到它)。实际上,您已为该术语撰写&" "[n1]。与其他添加表达式类似。

这解释了你得到的特殊输出。对于您要进行比较=的作业==,您也遇到了多个问题。