递增的int在函数末尾重置
Incremented int is resetting at the end of the function
这就是所讨论的函数。所讨论的变量是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
无n
5432
编辑:
下面有一个答案,由于某种原因被删除,似乎解决了我的问题。
答案是我应该用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;
}
相关文章:
- 在函数 'int main(int, char**) 中,没有声明 'MIN'
- 错误:无效使用非静态成员函数"int test::hotplug_callback(libusb_contex
- 重载函数 int vs double
- 错误 C2084:函数"int main(void)"已具有主体
- 无效使用非静态成员函数 int test::funcAB(int, int)
- 错误:函数"int open(...)"的隐式声明
- 如何在没有参数的情况下实现返回双向链表大小的函数?int size() const.
- 错误:参数太少,无法函数"int Solution(std::vector<int>, int)"
- arr++ 在函数"int f(int arr[])"中是什么意思?
- 带有声明帐户的C 构造函数(int = 0);
- 如何初始化一个在C++中期望向量和变量的构造函数<int>?
- C++,实现函数"int next(std::string param)"时出现奇怪的编译器错误
- 单链表交换函数(int,int)
- 插入 std::map<int, std::vector 的简短函数<int>>
- 函数int get()和istream&get(char&c)有什么区别
- 该函数 int f() 没有警告不返回任何值?
- 没有用于启动"ostream_iterator"的匹配构造函数<int>
- 函数"int __cdecl invoke_main(void)"中引用LNK2019未解析的外部符号_main错误 (?invoke_main@@YAHXZ)
- 函数"int (*function())[10];"是什么意思?
- 非成员函数 'int find(const T&)' 不能有 cv 限定符