繁体   English   中英

通过调用方法计算数组所有元素的乘积

[英]Calculates the multiplication of all elements of an array by calling the method

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

你的数组的长度是: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);

}
  1. multiplication应返回intlong (对于乘法,结果会增长得非常快)
  2. 删除myArray[] * 1; , 不需要, 1 对乘法是中性的
  3. 对于停止条件startIndex == endIndex只返回元素return myArray[endIndex]; . 你的回归 function 是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);

}

暂无
暂无

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

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