通过API文档查询Math的方法打印近似圆

来源:互联网 发布:诺基亚n8刷windows 编辑:程序博客网 时间:2024/05/29 19:06

通过API文档查询Math类的方法,打印出近似圆

          * *
     *             *
   *                 *
  *                   *
 *                     *
 *                     *
 *                     *
  *                   *
   *                 *
     *             *
           * *

只要给定不同的半径,圆的大小就会发生改变(如果需要使用复杂的数学运算,则可以查询Math方法)

import  java.util.Scanner;import java.lang.Math;public class MathTest { /**    * 未搞懂    * @param args    */    public static void main(String[] args) {        // TODO Auto-generated method stub        System.out.println("请输入圆的半径:");        Scanner in =new Scanner(System.in);        int radius = in.nextInt();//使用户能够从 System.in 中读取一个数        paint(radius);  //手动输入半径5      }    public static void paint(int r){        int y = r*2;//y=10        int x = 0;        int c = 0;        int z = 2;        for(int j=r*2;j>=0;j=j-z){//j>=0 && j<=10 j=8,            x=getX(r,y);            System.out.print(getSpace(x)+"*");            c=(r-x)*2;            System.out.println(getSpace(c)+"*");            y-=z;        }    }    public static int getX(int r,int y){            int x=y-r;//x=5            double t=Math.sqrt((r*r)-(x*x));            return (int)Math.round(r-t);    }    public static String getSpace(int i){        String s = " ";        for(int j=0;j<i;j++){            s+=" ";        }        return s;    }}

较为详细的解答

public static void main(String[] args){//调用绘图函数,参数是圆的半径paint(8);}public static void paint(int r){//假定圆心在坐标(r,r)处int x = 0;//x的坐标开始int y = 0;//y的坐标开始int c = 0;//中间空格数int z = 2;//每行递减量,步长设为2是为了调节屏幕纵横比。for (int i = 0; i <= r*2; i += z){//获取画*点的坐标的x值x = getX(r, y);//先画y值上左边的*System.out.print(getSpace(x)+"*");c = (r-x)*2;//以圆心对应输出空格//再画该y值上右边的*System.out.println(getSpace(c)+"*");//每次y值递减y += z;}}public static int getX(int r, int y){//取直角三角形长边长int h = y - r;//求直角三角形短边长double l = Math.sqrt((r*r)-(h*h));//取x值,Math.round()返回最接近的整数return (int) Math.round(r-l);} public static String getSpace(int i){ String s = ""; for(int j = 0; j<i; j++){ s += " "; } return s; }




阅读全文
0 0
原创粉丝点击