Java 画心形

来自姬鸿昌的知识库
跳到导航 跳到搜索
package org.example;

public class Heart {

    public static void main(String[] args) {

        //需要使用浮点数进行运算
        float x, y;

        //y轴控制的是图像的长度,因为图像打印是由上往下打印,根据图像y从正数开始
        //其中递减的值由实际情况调整
        for (y = 1.3f; y > -1.1f; y -= 0.15f) {

            //x轴控制的是图像的宽度,自左像右打印,根据图像x从负数开始
            for (x = -1.2f; x <= 1.2f; x += 0.05f) {

                //使用中间变量代替较长的运算
                float temp = x * x + y * y - 1;

                //pow方法作用是获取x的n次方,第一个参数是x,第二个参数为n
                double tempB = Math.pow(temp,3) - x*x*Math.pow(y, 3);

                if(tempB <= 0.0f) {
                    //由于unicode码不好进行对齐,所以这里使用 * 号代替
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }

            System.out.println();

        }//end for

    }

}