程序功能:
n个数字的连乘结果=N1*N2*N3*...*Nn,n的大小由用户输入时随意控制,所支持的最大连乘次数则在程序中通过final值设定(暂定为100,够长了吧)。
代码如下:
package example;
//JHTP Exercise 7.14: Variable-Length Argument List
//by pandenghuang@163.com
/**(Variable-Length Argument List) Write an application that calculates the product of a series
of integers that are passed to method product using a variable-length argument list. Test your method
with several calls, each with a different number of arguments.*/
import java.util.Scanner;
public class VariableArgs
{
public static double multiply(double[] factors){
double result=1.0;
for (double f:factors)
result*=f;
return result;
}
public static void main(String[] args)
{
final int SIZE=100;
double[] entry=new double[SIZE];
int count=0;
double number=0.1;
double result=0.0;
Scanner input=new Scanner(System.in);
for (int i=0;i<SIZE;i++){
System.out.print("请输入要连乘的数字(输入-1退出):");
number=input.nextDouble();
if(number==-1){
System.out.print("输入已结束。\n");
break;
}
entry[i]=number;
count++;
}
double[] factors=new double[count];
for (int i=0;i<count;i++)
factors[i]=entry[i];
result=multiply(factors);
System.out.printf("以上数字连乘的结果为:%.2f",result);
}
}
运行结果:
请输入要连乘的数字(输入-1退出):2.3
请输入要连乘的数字(输入-1退出):4.5
请输入要连乘的数字(输入-1退出):5.8
请输入要连乘的数字(输入-1退出):6.7
请输入要连乘的数字(输入-1退出):4.1235
请输入要连乘的数字(输入-1退出):5.468
请输入要连乘的数字(输入-1退出):-1
输入已结束。
以上数字连乘的结果为:9068.55