如何在Android中分割浮点数并将结果转换为整数 问题
假设如何在Android中分割浮点数并将结果转换为整数 问题,android,casting,integer,Android,Casting,Integer,假设int childCount=linearLayout.getChildCount()返回一个三加一的倍数,例如4,7,10,13 我想在childCount上加两个,然后除以三,得到我列表中数字的期望结果,例如(7+2)/3应该给出3的答案,但我不知道是2还是4,仅仅因为在执行浮点操作时出现了错误。所以我这样做是为了确保得到3,结果是: int numberOfCells = (int) ((linearLayout.getChildCount() + 2) / 3 + 0.5f); 对
int childCount=linearLayout.getChildCount()
返回一个三加一的倍数,例如4
,7
,10
,13
我想在childCount
上加两个,然后除以三,得到我列表中数字的期望结果,例如(7+2)/3
应该给出3
的答案,但我不知道是2
还是4
,仅仅因为在执行浮点操作时出现了错误。所以我这样做是为了确保得到3
,结果是:
int numberOfCells = (int) ((linearLayout.getChildCount() + 2) / 3 + 0.5f);
对吗
更新 因为在我的线性布局中,每个相对布局(也是线性布局的子视图)后面都有两个子视图(线)。但最后一个相对布局没有后续行。所以我想要得到的是相对布局的数量,也就是我要制作的列表中的单元格数量
更新2 是这样说的,
int numberOfCells = (int) ((linearLayout.getChildCount() + 2) / 3 + 0.5f);
相当于
int numberOfCells = (int) Math.floor((linearLayout.getChildCount() + 2) / 3 + 0.5f);
是这样说的,
int numberOfCells = (int) ((linearLayout.getChildCount() + 2) / 3 + 0.5f);
int numberOfCells=(int)((linearLayout.getChildCount()+2)/3+
0.5f)强>
相当于
int numberOfCells = (int) Math.floor((linearLayout.getChildCount() + 2) / 3 + 0.5f);
int numberOfCells=(int)Math.floor((linearLayout.getChildCount()+
2) /3+0.5f)强>
对
理由是:
两个方程的共同部分是:
(linearLayout.getChildCount() + 2) / 3 + 0.5f
让我们评估一下所有可能的结果
这里:linearLayout.getChildCount()+2将始终是一个+ve整数(linearLayout.getChildCount()+2)/3将计算为0
(当linearLayout.getChildCount()
返回0
)或+ve integer
。将0.5f添加到0
或+ve整数
将导致0.5f或+x.5f(其中x
是某个+ve整数)
因此,(linearLayout.getChildCount()+2)/3+0.5f的结果将是(0.5f或+x.5f)
现在,对于第一个方程,我们有:(int)(0.5f或+x.5f)。将浮点
或双精度
转换为int
将返回浮点或双精度的整数部分
第一个方程的可能结果:(0或+x)
对于第二个等式
,我们有:(int)Math.floor(0.5f或+x.5f)Math.floor(double)
返回小于或等于参数的最大正整数值。因此,数学地板(0.5f或+x.5f)将是:(最接近的+ve整数小于0.5f)=0.0
或(最接近的+ve整数小于+x.5f)=+x.0
。将它们强制转换为int
将导致(0或+x)
第二个等式的可能结果:(0或+x)
两个方程的计算结果相同。因此,它们是等价的
如何使用余数
?例如,假设:
int remainder = (linearLayout.getChildCount()) % 3;
int numberOfCells;
switch (remainder) {
case 1:
// linearLayout.getChildCount() returned 1, 4, 7, 10......
numberOfCells = (linearLayout.getChildCount() + 2) / 3;
break;
case 2:
// linearLayout.getChildCount() returned 2, 5, 8, 11......
numberOfCells = (linearLayout.getChildCount() + 1) / 3;
break;
default:
// linearLayout.getChildCount() returned a (+ve) multiple of 3......
numberOfCells = (linearLayout.getChildCount()) / 3;
break;
}
因此,如果子计数为2,则希望得到的结果为3。我不确定我是否完全理解你的问题。请看一下我的更新。更新2中的两个语句是等效的。现在,对于第一个等式,我们有:(int)(0.5f或+x.5f)
。将float
或double
转换为int
将返回float
或double
的整数部分。第一个方程的可能结果:(0或+x)
。在第二种情况下,我们有:(int)Math.floor(0.5f或+x.5f)
Math.floor(double)
返回小于或等于参数的最大正整数值。
因此,Math.floor(0.5f或+x.5f)
将是:(最接近的+ve整数小于0.5f)=0
或(最接近的+ve整数小于+x.5f)=+x
。