简体   繁体   English

可能会损失精度误差

[英]Possible loss of precision error

I have this question I am making a triangle class and in one code in the line that say int[]y coord I get this compiler error that says possible loss of precision required int found double but I am trying to add the square root(3)/2 to my get()y so Would not this be double. 我有一个问题,我正在制作一个三角形类,并在一行代码中说int [] y coord,我得到了这个编译器错误,该错误表明可能会损失精度,因此int找到了double,但我试图添加平方根(3 )/ 2到我的get()y,所以这不是两倍吗?

Help is appreciated. 感谢帮助。

import java.awt.*;

public class Triangle extends Shape {
    private int leng;

    public Triangle(int x, int y, Color color, int leng) {
        super(x, y, color);
        this.leng=leng;
    }

    public void draw(Graphics g) {
        int[]Xcoord={getX(),getX()+leng,getX()+leng/2};
        int[]Ycoord={getY(),getY(),getY()+Math.sqrt(3)/(2.0)};
        g.drawPolygon(Xcoord,Ycoord,3);
    }

    public int getHeight() {
        return leng;
    }

    public int getWidth() {
        return leng;
    }
}

The square root of 3 cannot be represented as an integer, as it's not an integer. 3的平方根不能表示为整数,因为它不是整数。 Make the array double[] : 使数组成为double[]

double[] Xcoord = { getX(), getX() + leng, getX() + leng / 2.0};
double[] Ycoord = { getY(), getY(), getY() + Math.sqrt(3) / (2.0)};

By the way, whitespace is recommended to be used to help readability, as I modified in the code I gave. 顺便说一下,正如我在给出的代码中所修改的那样,建议使用空格来提高可读性。

Your formula's not correct, either. 您的公式也不正确。 double alone won't fix it: 单独使用double不能解决问题:

    double [] Xcoord = { getX(), (getX()+leng), getX()+leng/2 );
    double [] Ycoord = { getY(), getY(), getY()*(1.0+Math.sqrt(3)/(2.0)) };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM