如何判断矩形是否是黄金矩形?

How to check whether rectangle is golden rectangle?

我有一个名为 Rectangle.The class 的 class class 有两个属性 width 和 height。 我需要检查矩形 class 是否有黄金比例(height/width = 1.6),如果有我需要 return true,否则 return false。

这是我的 class:

class Rectangle {
   private int x, y;
   private int height, width;

   public boolean isGoldenRatio()
   {
     return (height / width == 1 && height % width == 6); 
   }
}

我创建了函数 isGoldenRatio() 来检查边的比例。 但我猜这是错误的,因为我没有得到想要的结果。

更新: 我无法在 class 中定义加法字段,也无法使用数学库。

知道如何修复该功能吗?

如果你想要那个数字,你可以改变它以将它们转换为双精度并像这样进行比较

public boolean isGoldenRatio()
{
 return ((double)height / width == 1.6);
}

所有你需要做的就是除法,然后先将分子转换为 float。您还需要决定它必须有多接近才能算作黄金。

class Rectangle {
    private int x, y;
    private int height, width;
    private final static float FLOAT_THRESH = .01;

    public boolean isGoldenRatio()
    {
        return Math.abs(1.6 - (float)height / width) < FLOAT_THRESH;
    }
}

使用数学来避免使用浮点数。斐波那契数的比率在分母的平方内接近黄金比例。例如

1/1, 2/1, 3/2, 5/3, 8/5, 13/8, ...

分别在黄金比例的 1/1、1/1、1/4、1/9、1/25、1/64 ... 以内。

因此您可以完全使用整数或有理数进行数学计算。

如果想在小数点后两位以内近似21/13。所以检查是否

-1 <= 21*height - 13*width <= 1

或者高度和宽度互换反之亦然。

为了避免浮点数问题,您可以使用数学并简单地做

return (height * 10) == (width * 16);

为了解释它,你得到了等式:

H / W = 1.6       / multiply by 10
10 * H / W = 16   / multiply by W
10 * H = 16 * W