![](/img/trans.png)
[英]How do I make a method that calculates the variance of each element of an array from the mean of those elements using Java
[英]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);
}
multiplication
应返回int
或long
(对于乘法,结果会增长得非常快)myArray[] * 1;
, 不需要, 1 对乘法是中性的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.