增量int在函数结束时重置

时间:2015-12-05 03:11:44

标签: c++

这是有问题的功能。有问题的变量是count1。在return count1;之前,函数似乎将count1重置为1或2.最终cout行的结果是n行,其中n =尝试次数,包括正确答案。每行输出一个比下面一行高1的数字,直到count1 = 1或2.我无法确定最终输出的模式。

问题本身就是占位符。

地球上发生了什么?

注意:我是一个非常新的程序员,我知道有可能更有效的方法来做我正在做的事情,而我还没有学到。我愿意接受建议,但是由于我对C ++的不熟悉,我对这些建议的理解可能会受到阻碍

int q1(int count1)                      //q1() is always fed a value of 1.
{
    using namespace std;
    if (count1 <= 3)                    //User gets 3 tries to answer for full credit.
    {                                   //count1 is returned in order to determine user score.

        cout << "What is 2+2 \n";       //problem appears to occur between here and the end of this if statement.
        double a1;
        cin >> a1;

        if (a1 == 4)
        {
            cout << "Yup. You know what 2+2 is. \n\n";
        }
        else
        {
            wrong();                    //wrong() is a single line void function using std::cout and nothing else.
            q1(++count1);
        }
    }
    else
    {
        cout << "You have used all three tries. Next question. \n\n";
        ++count1;                       //count1 is incremented for an if statement in int main()
    }       
    cout << count1 << "\n";             //This line is strictly for debugging
    return count1;
}

最终cout行的输出看起来如下:
5
4
3
2
没有\n 5432

编辑:

以下答案因某些原因而被删除,似乎可以解决我的问题。

答案说明我应该用q1(++count1)

替换count1 = q1(++count1);

在我看来,这不应该奏效,但在实践中似乎有效。为什么呢?

1 个答案:

答案 0 :(得分:3)

使用递归时,第一次运行count1的函数是1(如你所说)。如果用户回答正确,那么你的函数将返回1,因为count1的值永远不会改变。

如果用户回答错误,则count1增加1并将其值赋予新函数(相同类型)。请记住,您传递了count1的值,这意味着新函数(第二个q1())将得到数字2,但会有一个新变量count1。它们可能具有相同的名称,但它们是不同的变量。

有两种方法可以解决您的问题:

通过使用指针,这样就可以传递count1的地址,并且每个函数都会更改相同的变量。 (这是最难的方式而不是最有效的方式)或

您可以像while那样进行递归调用,而不是进行递归调用:

int q1(int count1)
{
    using namespace std;
    while (count1 <= 3) //Run as long as user has chances
    {
        cout << "What is 2+2 \n";
        double a1;
        cin >> a1;

        if (a1 == 4)
        {
            cout << "Yup. You know what 2+2 is. \n\n";

            //Using `break` you stop the running `while` so the next
            //step is for the function to return
            break;
        }
        else
        {
            wrong();

            //By incrementing `count1` the next time the `while` runs
            //if user ran out of tries it will not enter the loop, so
            //it will return `count1` which would most likely be 4
            count1++;
        }
    }

    //Here the function is about to return, so you check if user won or lost
    if (count1 == 4)
        cout << "You have used all three tries. Next question. \n\n"; 

    //Debug
    cout << count1 << "\n";

    //Return
    return count1;
}
相关问题