递增的int在函数末尾重置

Incremented int is resetting at the end of the function

本文关键字:函数 int      更新时间:2023-10-16

这就是所讨论的函数。所讨论的变量是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. nn";
        }
        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. nn";
        ++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
n5432

编辑:

下面有一个答案,由于某种原因被删除,似乎解决了我的问题。

答案是我应该用count1 = q1(++count1); 代替q1(++count1)

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

使用递归时,函数第一次运行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. nn";
            //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. nn"; 
    //Debug
    cout << count1 << "n";
    //Return
    return count1;
}