【发布时间】:2017-11-27 16:54:07
【问题描述】:
我遇到了一个看起来是胭脂总变量的问题。 sumDigits 函数的目标是将用户输入的每个数字递归地添加到将显示的总数中。我现在发现的是,当我传递对输入总计的引用时,也接受了该值。我能解释一下发生了什么吗?
我的代码分解成简单的语句:
#include <iostream>
using namespace std;
int sumDigits(int&);
int main()
{
int input = 123;
cout << sumDigits(input);
}
int sumDigits(int& input)
{
int total, newNumber;
if (input < 10)
return input;
else
{
newNumber = input%10;
total += newNumber;
input = input/10;
return sumDigits(input);
}
}
我在测试验证总数时的代码:https://pastebin.com/u1MS63Ji
当前代码的结果:
Welcome to the Sum of Digits Machine. Please type in your number or -1 to
quit
enter a nonnegative integer: 1234
input: 1234
Total: 1234 // total magically takes input value
newNumber: 0
Total: 1234
Total after: 1238 newNumber: 4 //total+=newNumber does its job.
input: 123
input: 123
Total: 1539161746 //how in the world? 1238 + 3 does not equal this....
newNumber: 32600
Total: 1539161746
Total after: 1539161749 newNumber: 3
input: 12
input: 12
Total: 1539161746
newNumber: 32600
Total: 1539161746
Total after: 1539161748 newNumber: 2
input: 1
input: 1
number is smaller than 10
the sum of all digits is: 1.
enter a nonnegative integer:
有人可以向我解释一下为什么总在 sumDigits() 开始时会接收输入值吗?任何指出我做错了什么的指针都将不胜感激。
旁注:希望这个澄清解决了我的问题。如果不是管理员,请准确告诉我您想要什么,因为我显然是堆栈溢出的新手。我还应该解释我试图研究这个问题的反对票,但我运气不好。我还是个学生,对这方面很陌生。
【问题讨论】:
-
是时候学习如何使用调试器了。
-
我正在使用 Cloud 9,其中包含本机调试器。我已经追踪了两次,但仍然无法弄清楚它在哪里弄混了。
-
把你的代码放在这里,而不是“pastebin”。这些链接随时可能失效,使这个问题在未来变得毫无价值。取出 cmets、
cout's 和空行以供初学者使用。 -
例如this is what your code reduces down to,因此它将是minimal reproducible example。现在,使用它,我们不会滚动浏览大量不必要的 cmets 和多余的
cout行。此外,您可能会发现以这种方式呈现的代码存在问题。 -
明白了。我早些时候有点举手,因此为什么我把它放在目前的状态。谢谢指点。