繁体   English   中英

递归求和法

[英]Recursive Summation Method

我目前正在使用Java中的递归求和方法,到目前为止,这是我的代码,但是我在运行时遇到ArrayIndexOutOfBoundsException的一些问题。 至此,这是完整的代码。

   import java.util.Scanner;
   public class Summation {
   public static void main(String[] args) {
    input();
   }

    private static void input() {
       Scanner scanner = new Scanner(System.in);
        System.out.print("Lower bound: ");
        int lower = scanner.nextInt();
        System.out.print("Upper bound: ");
        int upper = scanner.nextInt();
        arrayForm(upper, lower);
   }

   private static void arrayForm(int upper, int lower) {
        int b = 0;
        int a = Math.abs(lower) + Math.abs(upper);
        int array[] = new int[a];
        for (int i = 0; i < array.length; i++) {
           array[i] = lower + i;
        }
       summation(array, b);
   }

   public static int summation(int array[], int b) {
       if (b > array.length) {
        System.out.println("Cannot continue");
        return 0;
    } else{
        int result = array[b] + summation(array, b + 1);
        System.out.println("recursion call: " + b);
        System.out.println("sum: " + result);
        System.out.println("parameter 1: " + array[b]);
        System.out.println("parameter 2: " + array[b + 1]);
        return result;
    }
  }
 }

您的代码中有两个错误:

  1. 修复b> = array.length:如果我给定范围1到10,则数组有11个元素。 这将导致索引从0到10。如果使用b = array.length调用array [b],则长度为11,并且超出范围。
  2. array.length-1:因为您正在调用sumsum(array,b + 1),所以索引b不能超过max-index-1。例如,界限:1到10。因此sumsum(array,10)调用sumsum(array,11) ),这就是数组中的最后一个元素。

因此sumsum(a,b)函数如下所示:

    public static int summation(int array[], int b) {
    if (b >= array.length - 1) {
        System.out.println("Cannot continue");
        return 0;
    } else {
        int result = array[b] + summation(array, b + 1);
        System.out.println("recursion call: " + b);
        System.out.println("sum: " + result);
        System.out.println("parameter 1: " + array[b]);
        System.out.println("parameter 2: " + array[b + 1]);
        System.out.println();
        return result;
    }

在其他部分:

   System.out.println("parameter 2: " + array[b + 1]);

需要有效索引:

b + 1 < array.length
b < array.length - 1

但是if-else仅保证:

b <= array.length
b < array.length + 1

因此应该

if (b >= array.length - 1) { ... } else { ... }

如果您打算这样做,那么逻辑中可能存在错误:

sum of lower + (lower + 1) + (lower + 2) + ... + upper

这些是平均(上+下)/ 2(上-下+1)项:

int sum = (upper - lower + 1) * (upper + lower) / 2;

这两个因素中的任何一个都是偶数,因为它们相差2*lower+1 ,所以整数计算是可以的:整数除以不会丢失任何内容。

sum(7, 9) = (9 - 7 + 1) * (9 + 7) = 3 * 16 = 48

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM