我最近刚开始编程并遇到了这个问题。
如何计算瓷砖地板需要多少 block 瓷砖? 地砖是一个宽度为20的正方形,地板的长度和宽度由用户输入。
我可以使用%计算出我需要多少个完整的瓷砖,但是一旦我到达侧面的瓷砖碎片,我就陷入了困境。允许切割成更小的条,只是不能制作马赛克。
我尝试将尺寸存储在列表中,并将它们添加到尽可能接近 20 的位置。但是后来我遇到了一些问题,例如使用 2 个 8 block 的瓷砖和 2 个 12 block 的使用 2 个瓷砖,而 2 block 瓷砖就足够了。
我似乎找不到一种方法来编写该逻辑。
final int tile = 20;
double length = Input.readDouble();
double width = Input.readDouble();
int completeColumTiles = (int)width/tile;
int completeRowTiles = (int)length/tile;
int tilesWithoutRest = completeRowTiles * completeColumTiles;
double restLength = length%tile;
double restWidth = width%tile;
int tilesRest = calculateRest(completeColumTiles, completeRowTiles, restLength, restWidth);
int tilesWithRest = tilesWithoutRest + tilesRest;
System.out.println("You need " + tilesWithRest + " tiles.");
所以基本上我需要关于calculateRest的帮助
最佳答案
获得这样的东西怎么样?
基本上,假设private static final int TILE_DIMENSION = 20;
,您需要:
private int getTilesCount(final int floorWidth, final int floorHeight) {
final int horizontalTiles = (floorWidth % TILE_DIMENSION) + ((floorWidth / TILE_DIMENSION) == 0) ? 1 : 0;
final int verticalTiles = (floorHeight % TILE_DIMENSION) + ((floorHeight / TILE_DIMENSION) == 0) ? 1 : 0;
return horizontalTiles * verticalTiles;
}
我在这个方法中所做的事情可以简单地分解如下:
- 计算每行中的图 block 数量 (
horizontalTiles
), - 计算每列中的图 block 数量 (
verticalTiles
),以及 - 返回这两个值的乘积。
以下是我计算每行/列中的图 block 数量的方法:
计算单行/列中可以容纳的图 block 数量:
floorWidth / TILE_DIMENSION
并添加 1 个图 block ,以防该行/列中剩余一些空白空间:
+ ((floorWidth / TILE_DIMENSION) == 0) ? 1 : 0;
<小时/>
顺便说一句,如果您还不知道,我在这里使用的语法 ((evalutaion) ? expression1 : expression2 ;
称为 Ternary Operator 。
它完全对应于doing(以伪代码形式):
variable result;
if (evaluation) {
result = expression1;
} else {
result = expression2;
}
关于java - 如何在 Java 中计算瓷砖地板需要多少 block 瓷砖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26371604/