简体   繁体   中英

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.

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. Make the array 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 [] Xcoord = { getX(), (getX()+leng), getX()+leng/2 );
    double [] Ycoord = { getY(), getY(), getY()*(1.0+Math.sqrt(3)/(2.0)) };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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