Java近似圆

效果图与原理图

                             

代码:

 1 public class Circle
 2 {
 3     public static void main(String[] args)
 4     {
 5         int radius = 10;
 6         System.out.println("输出半径为" + radius + "的近似圆");
 7         paint(radius);
 8     }
 9 
10     public static void paint(int r)
11     {
12         //假设圆心在(r, r)
13         int x;    //当前的x坐标
14         int y = 2 * r;   //当前的y坐标
15         int space;    //每行中间的空格数量
16         int d = 2;   //每行的递减量
17         for(int j = 2*r; j>=0; j=j-d)
18         {
19             x = getX(r, y);
20             space = 2 * (r-x);
21             System.out.print(getSpace(x+10) + "*");  //左边的*号,同时向右平移了10个单位
22             System.out.println(getSpace(space) + "*");   //右边的*号
23             y -= d;
24         }
25     }
26 
27     public static int getX(int r, int y)
28     {    {
29 
30         double tempX;
31         tempX = Math.sqrt(r*r - (y-r)*(y-r));
32         return (int)Math.round(-tempX +r); //Math.round(double d)返回最接近参数的 long,所以需要进行类型强制转换
33     }
34 
35     public static String getSpace(int space)
36     {
37         String s = "";
38         for(int i=0; i<space; i++)
39         {
40             s = s+" ";
41         }
42         return s;
43     }
44 }
View Code
原文地址:https://www.cnblogs.com/hyhl23/p/4064130.html