发现两年前写的代码与题目要求有较大出入(看来当时没搞清楚变长参数列表是怎么回事),改进如下:使用变长数组作为连乘方法的参数列表(注意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 |