Java语言运用数学思维,结合函数图像用“*”号打印出平面图形,以平行四边形,等腰三角形,六边形,菱形为例。
具体步骤:
- 通过双重for循环限制图像的x,y轴长度
- 通过图型的边界函数确认x,y的取值范围
- 注意:我们打印是由上至下打印,所以拿到图型要先进行镜像变换
1、平行四边形
代码如下:
//平行四边形
public static void parallelogram() {
for (int y = 0; y <= 10; y++) {
for (int x = 0; x <= 30; x++) {
if (y + x >= 10 && y + x <= 30) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println(" ");
}
}
结果如下:
2、等腰三角形
//等腰三角形
public static void triangle(){
for (int y = 0; y <= 10; y++) {
for (int x = 0; x <= 20; x++) {
if (y+x>=10 && x-y<=10) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println(" ");
}
}
3、六边形
//六边形
public static void hexagon(){
for (int y = 0; y <= 30; y++) {
for (int x = 0; x <= 20; x++) {
if (y+x>=10 && x-y<=10 && y+x<=40 && y-x<=20) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println(" ");
}
}
4、菱形
//菱形
public static void diamond(){
for(int y=0;y<=40;y++){
for (int x=0;x<=40;x++){
if((y+x)>=20 && (x-y)<=20 && (y-x)<=20 && (x+y)<=60)
{
System.out.print("*");
}else {
System.out.print(" ");
}
}
System.out.println(" ");
}
}