代码之家  ›  专栏  ›  技术社区  ›  MDS18

在构造函数中将int转换为float

  •  1
  • MDS18  · 技术社区  · 7 年前

    我有以下代码:

    public class Rectangle extends java.awt.Rectangle
    {
        private Position position;
    
    
    public Rectangle(Rectangle toCopy)
    {
        this.position = toCopy.position;
    }
    
    public Rectangle(Position position, int width, int height)
    {
        super(width, height);
        this.position = position;
    }
    

    这很好,但我需要的宽度和高度是浮动。问题是java中的构造函数。awt。矩形的宽度和高度采用int类型。有没有办法使宽度和高度在构造函数内浮动?

    3 回复  |  直到 7 年前
        1
  •  2
  •   Aaron N. Brock    7 年前

    我相信你在寻找 casting 。这允许您 float 变成一个 int 。您的示例中的实现是:

    public Rectangle(Position position, float width, float height) // Changed types to float
    {
        super((int) width, (int) height); // Cast from float to int
        this.position = position;
    
        // width & height are floats, like requested
    }
    
        2
  •  0
  •   SteelToe    7 年前

    只需使用如下方式将int转换为float: float myfloat = (float) myInt;

    所以改变这个:

          public Rectangle(Position position, int width, int height)
    {
    super(width, height);
    this.position = position;
    }
    

    对此:

       public Rectangle(Position position, int width, int height)
    {
    super((float) width,(float) height);
    this.position = position;
    }
    
        3
  •  0
  •   Elon_wang    7 年前

    也许你可以试试这个:

    int i;
    float f = i * 1.0f;