You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 + t1 which isn’t the standard Fibonacci recurrence. If your base case is F(n) = 1 for n <=1, the correct formula should be F(n) = F(n-1) + F(n-2).
  • Reusing the Same ARfib Instance: You create one newARfib object, use it for the n-1 call, then overwrite its n value for the n-2 call. 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-2 recursive call but doesn’t finish assigning its result to t2 or using it in the final calculation. The t2 variable 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 ARfib object for each recursive call (arFibMinus1 and arFibMinus2) to prevent state overlap.
  • Correct Recurrence: Replaced n + t1 with t1 + t2 to follow the standard Fibonacci logic matching your base case.
  • Completed n-2 Call: We finish the n-2 recursive flow, assign its result to t2, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:58:36