题目:通过API文档查询Math类的方法,打印出如右图所示的近似圆,只要给定不同半径,圆的大小就会随之发生改变(…)
话不多说,下面直接上我的代码
package test;
import java.lang.Math;
class Yuan
{
double r;//圆的半径
double x;//空格1打印的个数
double h;//空格2打印的个数
public Yuan(double r){
this.r=r;
}
public void print1(){//上半部分
for(double k=1;k<=r;k++){ //上半部分前r行
h=(int)(Math.sqrt(r*r-(r-k+1)*(r-k+1))); //k行打印空格2的个数
x=Math.round(r-h);//打印空格1的个数
for(double j=x;j>=0;j--) {//打印空格1 上
System.out.print(" ");
if(j==0) {
System.out.print("*");
}
}
for(double i=0;i<=(r-x)*2;i++) {//打印空格2 上
System.out.print(" ");
if(i==(r-x)*2) {
System.out.print("*");
}
}
System.out.println("\n");
}
}
/* ****************************
* ****************************
* ****************************/
public void print2(){//下半部分
for(double z=r;z>=1;z--){ //下半部分前r行
h=(int)(Math.sqrt(r*r-(r-z+1)*(r-z+1))); //k行打印空格2的个数
x=Math.round(r-h);//打印空格1的个数
for(double j1=0;j1<=x;j1++) {//打印空格1 下
System.out.print(" ");
if(j1==x) {
System.out.print("*");
}
}
for(double i=(r-x)*2;i>=0;i--) {//打印空格2下
System.out.print(" ");
if(i==0) {
System.out.print("*");
}
}
System.out.println("\n");
}
}
//*************************************************
public static void main(String[] args)
{
Yuan y1=new Yuan(8);
y1.print1();
y1.print2();
}
}