【问题标题】:Calculates the multiplication of all elements of an array by calling the method通过调用方法计算数组所有元素的乘积
【发布时间】:2020-05-18 08:50:17
【问题描述】:

我需要关于数组乘法的帮助。这是我到目前为止所得到的,我不确定如何继续。这个问题需要我使用递归。输出应如下所示:

你的数组长度是:6

你的数组元素是:1 2 3 4 5 6

{1, 2, 3, 4, 5, 6} 的乘积是 720。

我不想要一个确切的答案,而是对我可以做/研究的事情的解释,尽管如果你愿意,你可以提供一个工作代码,谢谢。


public static void main(String[] args) {

    Scanner userInput = new Scanner(System.in);

    System.out.printf("The length of your array is: ");
    int Length = Integer.parseInt(userInput.nextLine());
    System.out.printf("The elements of your array are: ");
    int[] myArray = new int[Length];
    //Determines Length of array based on user input
    for (int i = 0; i < Length; i ++) {
        myArray[i] = Integer.parseInt(userInput.next());
    }
    //Is the defined elements in array, based on user input
    System.out.printf("The multiplication is %s%n", multiplication(myArray, 0, Length - 1));
}

public static String multiplication(int[] myArray, int startIndex, int endIndex) {

    myArray[] * 1;
    if (startIndex == endIndex)
        return myArray[endIndex] + ".";
    else
        return myArray[startIndex]+ multiplication(myArray, startIndex + 1, endIndex);

}

【问题讨论】:

    标签: java arrays recursion methods


    【解决方案1】:
    1. multiplication 应该返回 intlong(对于乘法,结果会增长得非常快)
    2. 去掉myArray[] * 1;,不需要,1是乘法中性
    3. 对于停止条件startIndex == endIndex,只需返回元素return myArray[endIndex];。您的康复功能是 f(n) = n * f(n-1)
    public static long multiplication(int[] myArray, int startIndex, int endIndex) {
        if (startIndex == endIndex)
            return myArray[endIndex];
        else
            return myArray[startIndex] * multiplication(myArray, startIndex + 1, endIndex);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-12
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 2021-12-10
      • 2016-12-29
      • 2016-01-08
      • 2017-05-13
      • 1970-01-01
      相关资源
      最近更新 更多