学以致用——Java源码——使用变长参数列表实现n个数的连乘(Variable-Length Argument List)

发现两年前写的代码与题目要求有较大出入(看来当时没搞清楚变长参数列表是怎么回事),改进如下:使用变长数组作为连乘方法的参数列表(注意public static double multiply(double... factors)一句中的省略号即表示变长参数)。

之前的代码参考:

https://blog.csdn.net/hpdlzu80100/article/details/51851067

代码如下:

package exercises.ch7Arrays;

	//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.*/
	 
	public class VariableLengthArgList
	{
		public static double multiply(double... factors){  //Using variable-length argument lists.
			double result=1.0;
			for (double f:factors)
				result*=f;
			return result;
		}
		
		public static void main(String[] args)
	{
		      double d1 = 19.93;
		      double d2 = 19.96;
		      double d3 = 20.06;
		      double d4 = 20.13;

		      System.out.printf("d1 = %.2f%nd2 = %.2f%nd3 = %.2f%nd4 = %.2f%n%n",
		         d1, d2, d3, d4);

		      System.out.printf("Product of d1 and d2 is %.2f%n", 
		    		  multiply(d1, d2)); 
		      System.out.printf("Product of d1, d2 and d3 is %.2f%n", 
		    		  multiply(d1, d2, d3));
		      System.out.printf("Product of d1, d2, d3 and d4 is %.2f%n", 
		    		  multiply(d1, d2, d3, d4));
	 
	}
	}

运行结果:

d1 = 19.93

d2 = 19.96

d3 = 20.06

d4 = 20.13

 

Product of d1 and d2 is 397.80

Product of d1, d2 and d3 is 7979.92

Product of d1, d2, d3 and d4 is 160635.87

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值