瘋狂java 講義第三章練習題---畫圓
阿新 • • 發佈:2019-01-06
public class PaintRound{ /** * @author Dream_e. * @version v1.0 */ private int r;//圓的半徑 PaintRound(int r){ this.r = r; } public void paint(){ int y = 2*r;//y的最大值為半徑的2倍 int x = 0; int c = 0; int z = 2;//座標軸遞減量. for(int j = y; j >= 0; j-=z){ x = getX(r,y); System.out.print(getSpace(x)+"*"); c = (r-x)*2; System.out.println(getSpace(c)+"*"); y-=z; } } //計算X座標. private int getX(int r, int y){ double temp = Math.sqrt(r*r-(r-y)*(r-y));//根據圓內的正角三角形計算出圓上某點到圓心的X軸距離 int x = (int)Math.round(r-temp); return x; } //計算要列印的空格數量. private String getSpace(int c){ String space = " "; for(int i = 0; i < c; i++){ space += " "; } return space; } public static void main(String[] args){ new PaintRound(10).paint(); } }