常數變易法
阿新 • • 發佈:2017-05-07
.cn 是我 open 字符 println 空格 ima 輸出* clas
思路:
現將變動部分用常數代替,再逐步將常數替換為變數(變量)
關鍵是尋找變化的規律,如果不直觀,可以列出所有變化,進行比對,然後設計公式
實例:
1.輸出三角星號
首先找規律,發現每一行都是先輸出空格,然後輸出*號,空格、信號與行號的關系如下:
行號 空格數 星號數
1 4 1
2 3 2
3 2 3
4 1 4
5 0 5
代碼:
public static voidmain(String[] args) { int rows = 5; for (int i = 1; i <= rows; ++i) { for (int j = 1; j <= rows - i; ++j) { System.out.print(" "); } for (int j = 1; j <= i; ++j) { System.out.print("* "); } System.out.println(); } }
2.輸出字母金字塔
經過觀察,可以發現每一行的字符從左到右都是先增大再減小,最大的字符都是‘A’ + 行號-1(行號從1開始)
public static void main(String[] args) { { int rows = 5; char ch = ‘A‘; for (int i = 1; i <= rows; ++i) { for (int j = 1; j <= rows - i; ++j) { System.out.print(‘ ‘); }for (int j = 0; j <= i - 1; ++j) { System.out.print((char) (ch + j)); // 將ASCII碼轉換為字符 } for (int j = i - 2; j >= 0; --j) { System.out.print((char) (ch + j)); } System.out.println(); } }
當編程逐漸熟練之後,常數變異法可能是我們最常用的方法。
3.輸出以下圖形
代碼:
public static void main(String[] args) { { int rows = 13; if (rows % 2 == 0) //由於圖形對稱,處理偶數行,使其變為奇數行 rows += 1; for (int i = 1; i<= rows/2; ++i) { for(int j = 0; j < i; ++j) System.out.print(‘ ‘); System.out.print("$$"); for(int j = 0; j < rows /2 -i; ++j) System.out.print(" "); System.out.print("$$"); System.out.println(); } for(int i = 1; i <= rows/2+1; ++i) System.out.print(‘ ‘); System.out.println("$$"); for (int i = 1; i<= rows/2; ++i) { for(int j = 0; j < rows/2+1 -i; ++j) System.out.print(‘ ‘); System.out.print("$$"); for(int j = 0; j < i - 1; ++j) System.out.print(" "); System.out.print("$$"); System.out.println(); } }View Code
常數變易法