这个程序必须计算铺地板需要多少块瓷砖。瓷砖为 8 英寸 x 8 英寸。瓷砖可以作为一个整体使用,也可以使用瓷砖的一部分。一块瓷砖只能切出一块可用的部分。也就是说,如果从瓷砖上切下一块,则必须将瓷砖的其余部分扔掉。该程序接受房间的长度和宽度,并返回使用了多少整块瓷砖以及使用了多少部分瓷砖。长度以英寸为单位。
我已经尝试过这个问题并且没有问题获得所需的完整瓷砖数量但我似乎没有运气需要的部分瓷砖数量。我为此编写了这个程序。
#include<stdio.h>
int main()
{
int l,b,full,l1,bl,part;
float ar2,ar3;
scanf("%d%d,&l,&b);
ar3=(float)(l*b)/64;
l1=l/8;
bl=b/8;
full=l1*bl;
ar2=ar3-full;
part=ar2*2;
printf("%d\n%d",full,part);
return 0;
}
常见的方法是让瓷砖与墙壁平行。在这种情况下,您只需找出两个方向所需的瓷砖数量,瓷砖的总数就是这两个数字的乘积。获取部分图块数量的技巧是分别计算整个图块的数量,然后计算整个 和 部分图块的数量。代码变为:
#include<stdio.h>
int main()
{
int l,b,full,l1,bl,part;
int partl = 0, partb = 0;
scanf("%d%d",&l,&b);
l1=l/8; // number of whole tiles
if ((l % 8) != 0) {
partl = 1; // will need one partial at the end
}
// second direction
bl=b/8;
if ((b % 8) != 0) {
partb = 1; // will need one partial at the end
}
full=l1*bl; // total number of whole tiles
if (partl) l1 += 1; // total (including partial) per direction
if (partb) bl += 1;
part = l1 * bl - full; // partial is total - number of whole tiles
printf("%d\n%d",full,part);
return 0;
}
在任一方向上有 0 行或 1 行部分瓷砖。如果两个方向都有部分瓷砖,那么也有部分角落瓷砖。
您可以使用取模运算符
%
来查找是否有任何部分瓷砖:
// Calculation of partial tiles
part = 0;
int partL = l%8;
int partB = b%8;
if (partL > 0) {
part += bl; // Partial tiles along one edge
}
if (partB > 0) {
part += l1; // Partial tiles along the other edge
}
if (partL > 0 && partB > 0) {
part += 1; // Partial corner tile;
}
注:
l
和 1
的字形通常很难区分,因此在变量名中使用它们时要小心。如果你不假思索地使用它们,代码将更难阅读。
width = int(input())
length = int(input())
full_tiles_length=length//8
full_tiles_width =width//8
frac_length = (length/8)%1
frac_width =(width/8)%1
cl=0
cw=0
if(frac_width!=0 ):
cw =full_tiles_length
if(frac_length!=0):
cl =full_tiles_width
print(full_tiles_length*full_tiles_width)
if(cl!=0 and cw!=0):
print(cl+cw+1)
else:
print(cl+cw)