shaokel 2019-12-04 17:57 采纳率: 95.2%
浏览 125
已采纳

请求大佬支援!!!递归返回错误

结果应该是38.但是返回的却是21

public static void main(String[] args) {
        int[] a = {2,5,3,9,12,7};
        System.out.println(test3(a,0,a.length-1));
    }

private static int test3(int[] a,int begin,int end) {

        int mid = (begin + end)/2;

        if(mid==begin)
            return a[begin];
        if(mid==end)
            return a[end];

        return test3(a,begin,mid)+test3(a,mid+1,end);


    }

  • 写回答

1条回答

  • Kevin.Y.K 2019-12-04 18:23
    关注
    public static void main(String[] args) {
            int[] a = {2,5,3,9,12,7};
            System.out.println(test3(a,0,a.length-1));
        }
    
        private static int test3(int[] a,int begin,int end) {
    
            if(end-begin>=2) {
                int mid = (begin + end)/2;
    
                if(mid==begin) {
                    return a[begin];
                }
                if(mid==end)
                    return a[end];
                return test3(a,begin,mid)+test3(a,mid+1,end);
            }else if(end-begin==1){
                return a[begin]+a[end];
            }else {
                return a[begin];
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已采纳回答 10月9日

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?