【问题标题】:Making a hexagon using circle formula使用圆形公式制作六边形
【发布时间】:2021-02-23 00:28:00
【问题描述】:

所以我尝试使用点 rsin(theta) 和 rcos(theta) 公式制作六边形,但公式中似乎有一些错误。当把它写在纸上时,公式有效,但感觉好像我忽略了一些东西......

public static void drawHexagon(double len, double xc, double yc, int angle)
{
    if(angle <= -360)
        angle = 0;
    double rotAngX = (len*Math.cos(angle));
    double rotAngY = (len*Math.sin(angle));
    //System.out.println(rotAngX + " " + rotAngY + " " + Math.cos(-30));
    /*double [] x = {(xc - len*(Math.sqrt(3)/2.0)), xc,
        xc + len*(Math.sqrt(3)/2.0), xc + len*(Math.sqrt(3)/2.0),
        xc, xc - len*(Math.sqrt(3)/2.0)};
    double [] y = {yc + len/2.0, yc + len, yc + len/2.0,
            yc - len/2.0, yc - len, yc - len/2.0};*/
    double[] x = new double[6];
    double[] y = new double[6];
    int[] angles = { 150, 90, 30, 330, 270, 210 };
    for(int i = 0; i < 6; i++) {
        x[i] = xc + (len*Math.cos(angles[i]));
        y[i] = yc + (len*Math.sin(angles[i]));
    }
    printPoints(x, y);
    StdDraw.setPenColor(Color.CYAN);
    StdDraw.filledPolygon(x,y);
    StdDraw.setPenColor(Color.PINK);
    StdDraw.polygon(x,y);
}

注释掉的部分有效,但我正在尝试旋转它们,因此在 for 循环中会将角度参数添加到角度 [i]。我在 for 循环中做错了什么?

这是代码的结果。六边形但不是真的:

【问题讨论】:

  • 您不需要对角度进行硬编码。 for (int i = 0; i &lt; 6; i++) { angle += 360.0 / 6; x=len*cos(angle); y=len*sin(angle); /* draw line to xc+x, yc+y */ }
  • 试过了,但还是没有显示为六边形
  • Math.cos 和 sin 使用弧度
  • 好的,应该是angle += 2.0 * Math.PI / 6;

标签: java user-interface geometry draw


【解决方案1】:

Math.sin 的 Javadoc 说:

public static double sin​(double a)

返回一个角度的三角正弦值。 [...]

参数:

a - 一个角度,以弧度为单位。

您的代码以度为单位传递角度,而不是radians

您可以先转换角度:

Math.sin(Math.toRadians(30))

或直接以弧度指定角度:

Math.sin(Math.PI / 6);

【讨论】:

    【解决方案2】:

    我不确定你要做什么,但这是这样吗?:

    public static void drawHexagon(double len, double xc, double yc, int angle)
    {
        double[] x = new double[6];
        double[] y = new double[6];  
        x[0] = len*Math.cos(3.14*angle/180.0);
        y[0] = len*Math.sin(3.14*angle/180.0);
        double cos_60; 
        double sin_60;
        cos_60 = 1.0/2.0;
        sin_60 = Math.sqrt(3.0)/2.0;
        for(int i = 1; i < 6; i++) {
            x[i] = xc + cos_60*x[i-1] - sin_60*y[i-1];
            y[i] = yc + sin_60*x[i-1] + cos_60*y[i-1];
        }
        printPoints(x, y);
        StdDraw.setPenColor(Color.CYAN);
        StdDraw.filledPolygon(x,y);
        StdDraw.setPenColor(Color.PINK);
        StdDraw.polygon(x,y);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多