打印圓

package com.dailei.fengkuangjava;

import java.util.Scanner;

public class PrintCircle {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new PrintCircle().circle();

	}

	public void circle() {
		System.out.print("please input r=");
		//從鍵盤讀出半徑r
		Scanner str = new Scanner(System.in); 
		int r = str.nextInt();
		//開始畫圓。
        //y爲圓上點的縱座標。
        //步長設爲2是爲了調節屏幕縱橫比。由於屏幕的行距大於列距,不進行調節顯示出來的將是橢圓。
		for (int y = 0; y <= 2 * r; y += 2) {
			// 定義點的近似橫座標
			long x = Math.round(r - Math.sqrt(2 * r * y - y * y));
			// 定義相同縱座標的兩個點之間的橫座標距離
			long longLength = 2 * (r - x);
			// 打印圓上的點左邊的空格
			for (int i = 0; i <= x; i++) {
				System.out.print(' ');
			}
			// 打印圓上同一縱座標左邊的點
			System.out.print('*');
			// 打印圓上同一縱座標的兩點之間的空格
			for (int j = 0; j <= longLength; j++) {
				System.out.print(' ');
			}
			// 打印圓上同一縱座標右邊的點
			System.out.println('*');
		}
	}
}
相關文章
相關標籤/搜索