似乎应该有一种使用for()循环编写product()调用的方法。我不知道该怎么做。有人知道吗?
// store numbers
int[] i = { 1, 7, 2, 4, 6, 54, 25, 23, 10, 65 };
System.out.println(product(i[0]));
System.out.println(product(i[0], i[1]));
........
System.out.println(product(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8], i[9]));
public static int product(int... num) {...}
我已经写了产品,我只需要用从product(i [0])到product(i [0],i [1],i [2] ...,[9]的参数调用product。
最终代码:
// Calculate product of any amount of numbers
public static void main(String[] args)
{
// create Scanner for input
Scanner in = new Scanner(System.in);
// store numbers
int[] array = { 1, 7, 2, 4, 6, 14, 25, 23, 10, 35 };
for (int j = 1 ; j <= array.length; j++) {
// Construct a temporary array with the required subset of items
int[] tmp = new int[j];
// Copy from the original into the temporary
System.arraycopy(array, 0, tmp, 0, j);
// Make a call of product()
System.out.println(product(tmp));
} // end for
} // end method main
public static int product(int... num)
{
// product
int product = 1;
// calculate product
for(int i : num)
product *= i;
return product;
} // end method product
您需要int
使用所需数量的项目创建一个的临时数组,将的子数组复制i
到该临时数组中,然后将其传递为product
:
for (int count = 1 ; count <= i.length() ; count++) {
// Construct a temporary array with the required subset of items
int[] tmp = new int[count];
// Copy from the original into the temporary
System.arraycopy(i, 0, tmp, 0, count);
// Make a call of product()
System.out.println(product(tmp));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句