n个数字连乘的计算(Variable-Length Argument List)

程序功能:

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

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值