通过API文档查询Math类的方法,打印出如下所示的近似圆,只要给定不同半径,圆的大小就会随之发生改变。如图:
import java.util.Scanner;
public class PrintCircleByMath {
private static final int V = 2;
public static void main(String[] args) {
System.out.println("Please enter the radius of the circle:");
Scanner in = new Scanner(
System.in);
int radius = in.nextInt();
PrintCircleByMath.paintCircle(radius);
}
public static void paintCircle(int r){
int yuan_xin_x = r * V;
int yuan_xin_y = r;
String[][] bk = new String[yuan_xin_y*2+1][yuan_xin_x*2+V];
for (int i=0; i < yuan_xin_y*2+1; i++){
for (int j=0; j < yuan_xin_x*2+V; j++){
bk[i][j] = " ";
}
}
bk[0][yuan_xin_x] = bk[0][yuan_xin_x + 1] = "*";
bk[yuan_xin_y*2][yuan_xin_x] = bk[yuan_xin_y*2][yuan_xin_x + 1] = "*";
bk[yuan_xin_y][0] = bk[yuan_xin_y][yuan_xin_x * 2 + 1] = "*";
for (int i = 1; i < yuan_xin_y; i++){
int y = yuan_xin_y - i;
int x_2 = Math.round((float) Math.sqrt(r*r - y*y));
int x = yuan_xin_x - x_2*2;
bk[i][x] = bk[i][yuan_xin_x * 2 + 1 - x] = "*";
bk[yuan_xin_y*2 - i][x] = bk[yuan_xin_y*2 - i][yuan_xin_x * 2 + 1 - x] = "*";
}
for (int i=0; i < yuan_xin_y*2+1; i++){
for (int j=0; j < yuan_xin_x*2+V; j++){
System.out.print(bk[i][j]);
}
System.out.println();
}
}
}
|