學以致用——Java原始碼——使用變長引數列表實現n個數的連乘(Variable-Length Argument List)
阿新 • • 發佈:2018-12-30
發現兩年前寫的程式碼與題目要求有較大出入(看來當時沒搞清楚變長引數列表是怎麼回事),改進如下:使用變長陣列作為連乘方法的引數列表(注意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 [email protected]
/**(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 |