简体   繁体   English

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

[英]Converting int to float in constructor

I have the following code: 我有以下代码:

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;
}

This works fine, however I need width and height to be floats. 这很好,但是我需要宽度和高度为浮点数。 The problem is the constructor in java.awt.Rectangle takes in an int type for width and height. 问题是java.awt.Rectangle中的构造函数采用了一个int类型来表示宽度和高度。 Is there any way to make width and height floats within the constructor? 有什么方法可以使宽度和高度在构造函数中浮动吗?

I believe you're looking for casting . 我相信您正在寻找casting This allows you to turn an float into a int . 这使您可以将float转换为int The implementation in your example would be: 您的示例中的实现为:

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
}

Just cast the int to a float using casting like this: float myfloat = (float) myInt; 只需使用如下的强制转换将int转换为float: float myfloat = (float) myInt;

So change this: 所以改变这个:

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

To This: 为此:

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

Maybe you can try this: 也许您可以尝试以下方法:

int i;
float f = i * 1.0f;

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

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