Calling methods from within other methods
------------------------程序如下:-----------------------------
/* * File: Combinations.java * ----------------------- * This program computes the mathematical combinations function * C(n, k), which is the number of ways of selecting k objects * from a set of n distinct objects. */
package chapter5; import java.util.Scanner;
public class Combinations {
public void run(){ int n; int k; int result; System.out.println("please input the n:"); Scanner input=new Scanner(System.in); n=input.nextInt(); System.out.println("please input the k:"); Scanner input1=new Scanner(System.in); k=input1.nextInt(); result=Combinations(n,k); // 调用函数Combinations(int n,int k) System.out.println("C("+n+","+k+")="+result); } // 计算C(n,k)=n!/(k!*(n-k)!) private static int Combinations(int n,int k){ int result; result=factorial(n)/(factorial(k)*factorial(n-k)); // 调用函数factorial(int n) return result; } // 计算n! private static int factorial(int n) { int result=1; for(int i=1;i<=n;i++){ result*=i; } return result; } }
-------------------------运行程序-----------------
|
请发表评论