You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java控制台中打印实心圆形?

如何在Java控制台打印实心圆形

你的代码输出空心圆形是因为当前条件只筛选出了圆周附近的点。要打印实心圆形,需要判断每个点到圆心的距离小于等于半径,也就是满足 x² + y² ≤ r²(x为当前点与圆心的水平距离,y为垂直距离)。

修改后的代码如下:

public class test0 {
    public static void circle(int posX, int posY, int rad) {
        // 遍历覆盖圆心上下左右整个圆形区域的行
        for (int i = posX - rad; i <= posX + rad; i++) {
            // 遍历覆盖圆心左右整个圆形区域的列
            for (int j = posY - rad; j <= posY + rad; j++) {
                int xDiff = i - posX;
                int yDiff = j - posY;
                // 判断点是否在圆内或圆上
                if (xDiff * xDiff + yDiff * yDiff <= rad * rad) {
                    System.out.print("#");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }

    public static void main(String args[]) {
        circle(5, 10, 5);
    }
}

额外优化说明:

  • 原代码循环范围未覆盖圆心左侧和上方区域,修改后从posX - rad到posX + rad,确保整个圆形完整绘制
  • 直接比较距离平方,避免开根号运算,效率更高

内容的提问来源于stack exchange,提问作者YahyaB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 07:33:11