使用Runtime Stack实现输出错误,请求技术协助排查
Fixing Your Runtime Stack-Based Fibonacci Implementation
Hey there, let's work through why your ARFib class is returning incorrect results when using a Runtime Stack. I’ve spotted several key issues in your code—let’s break them down and fix them step by step:
Key Problems in Your Current Code
- Wrong Fibonacci Formula: You’re calculating
returnVal = n + t1which isn’t the standard Fibonacci recurrence. If your base case isF(n) = 1forn <=1, the correct formula should beF(n) = F(n-1) + F(n-2). - Reusing the Same ARfib Instance: You create one
newARfibobject, use it for then-1call, then overwrite itsnvalue for then-2call. This can lead to unexpected state leakage between recursive calls, especially if your Runtime Stack retains references to the object after popping. - Unused t2 & Incomplete n-2 Call: Your code starts the
n-2recursive call but doesn’t finish assigning its result tot2or using it in the final calculation. Thet2variable is defined but never utilized, which is a red flag.
Corrected ARfib Class Implementation
Here’s a revised version of your code that fixes these issues:
class ARfib { int n; // Parameter int t1, t2; // Temporary variables int returnVal; static int count = 0; void fib() { count++; if (n <= 1) { returnVal = 1; // Base case: F(0) = 1, F(1) = 1 } else { // Handle F(n-1) ARfib arFibMinus1 = new ARfib(); arFibMinus1.n = n - 1; RuntimeStack.push(arFibMinus1); arFibMinus1.fib(); t1 = arFibMinus1.returnVal; RuntimeStack.pop(); // Handle F(n-2) ARfib arFibMinus2 = new ARfib(); arFibMinus2.n = n - 2; RuntimeStack.push(arFibMinus2); arFibMinus2.fib(); t2 = arFibMinus2.returnVal; RuntimeStack.pop(); // Correct Fibonacci recurrence returnVal = t1 + t2; } } }
Quick Notes on the Fixes
- Separate Instances: We create a new
ARfibobject for each recursive call (arFibMinus1andarFibMinus2) to prevent state overlap. - Correct Recurrence: Replaced
n + t1witht1 + t2to follow the standard Fibonacci logic matching your base case. - Completed n-2 Call: We finish the
n-2recursive flow, assign its result tot2, and use it in the final calculation.
If you’re still getting unexpected results, double-check that your RuntimeStack implementation correctly handles pushing/popping objects without modifying their state while they’re on the stack.
内容的提问来源于stack exchange,提问作者Parth Mehta
相关产品推荐
相关产品推荐

