課堂作業02程序設計
源代碼:
package yang1;
import java.math.BigInteger;
import java.util.Scanner;
public class Yang1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("求組合數C(n,k):(n為下標)");//用戶輸入
System.out.print("請輸入n,k:");
Scanner scan = new Scanner(System.in
int n = scan.nextInt();
int k = scan.nextInt();
if(n<k)
System.out.println("ERROR!");
else if(n==0&&k==0)
System.out.println("1");
else
System.out.print("C("+n+","+k+")="+Calculate(n)/Calculate(k)/Calculate
}
public static long Calculate(int n) {
if(n==1)
{
return 1;
}
return n*Calculate(n-1);
}
}
結果截圖:
源代碼:
package yang2;
import java.math.BigInteger;
import java.util.Scanner;
public class Yang2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("求組合數C(n,k):(n為下標)");//用戶輸入
System.out.print("請輸入n,k:");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
if(n<k)
System.out.println("ERROR!");
else if(n==0&&k==0)
System.out.println("1");
else
System.out.print("C("+n+","+k+")="+Calculate(n)/Calculate(k)/Calculate(n-k));
}
public static long Calculate(int n) {
if(n==1)
{
return 1;
}
return n*Calculate(n-1);
}
}
結果截屏:
源代碼:
package yang3;
import java.util.Scanner;
public class Yang3 {
public static void main(String[] args){
System.out.println("請輸入組合數C(n,k)的兩個變量n和k:");
Scanner in1=new Scanner(System.in);
int n = in1.nextInt();
Scanner in2=new Scanner(System.in);
int k = in2.nextInt();
System.out.println("結果為:"+C(n,k));
in1.close();
in2.close();
}
public static int C(int m,int a)
{
if(m<0||a<0||m<a)
return 0;
if(m==a)
return 1;
if(a==1)
return m;
return C(m-1,a)+C(m-1,a-1);
}
}
結果截屏:
程序設計流程圖:
源代碼:
package hannuota;
import java.util.Scanner;
public class Hannuota {
public static void solveTowers(int disks,int sourcePeg,int destinationPeg,int tempPeg)
{
if(disks == 1)
{
System.out.printf("\n%d --> %d",sourcePeg,destinationPeg);
return;
}
solveTowers(disks-1,sourcePeg,tempPeg,destinationPeg);
System.out.printf("\n%d --> %d",sourcePeg,destinationPeg);
solveTowers(disks-1,tempPeg,destinationPeg,sourcePeg);
}
public static void main(String[] args)
{
System.out.println("請輸入盤子數:");
Scanner N = new Scanner(System.in);
int n = N.nextInt();
System.out.print("移動方法為:");
solveTowers(n,1,3,2);
N.close();
}
}
結果截屏:
第三題:
使用遞歸方法判斷,某個字符串是否回文。
設計思想:
定義一個字符串,判斷它是否是回文數。地冠以兩個指針,一個指向最前端,一個指向最後段,依次判斷第一個字符與最後一個字符是否相等,如果都相等,返回ture;若期間有不相等,則直接返回false。
程序流程圖:
源代碼:
package huiwen;
public class Huiwen {
public static boolean isHuiwen(String s,int i,int j)
{ if(i>j) throw new IllegalArgumentException();
if(i == j) return true;
else{ return (s.charAt(i)==s.charAt(j))&& isHuiwen(s,i+1,j-1); }
}
public static void main(String[] args) {
String test = "ABCBA";
int i=0; int j=test.length()-1;
System.out.println(test + " is Palindrome?" + Huiwen.isHuiwen(test, i, j));
}
}
結果截圖:
課堂作業02程序設計