检查计算的输出是否为整数 [英] Checking if the output of a calculation is a whole number
问题描述
检查计算输出是否为整数的方法是什么?我尝试这样做:
What is a method to check if the output of a calculation is a whole number? I've tried doing this:
if ((i / 3) is Int ) {
print("Whole Number")
}
但是它似乎正在检查变量的类型,而不是输出的内容.
But it seems to be checking the type of the variable, not what the output is.
显然,如果变量是整数,它将自动舍入操作的输出,因此我必须执行以下操作:
Apparently if the variable is an integer, it automatically rounds the output of the operation, so I had to do something like this:
if((i.toFloat()/3) == (i / 3).toFloat()){
println("Whole Number")
推荐答案
一种简单的检查a / b
是否为整数的方法是检查余数是否为零:a % b == 0
.
An easy way to check whether a / b
is a whole number is to check the remainder for being zero: a % b == 0
.
但是,请注意,如果/
的两个操作数均为整数类型(Short
,Int
,Long
),则除法结果将始终为整数(小数部分将被删除) ),因此,如果您有val i: Int = 2
,则i % 3 == 1
但i / 3 == 0
.要使用分数除法,请至少对一个操作数进行分数运算,例如i / 3.0
或i.toDouble / 3
.
Note, however, that if both operands of /
are of an integral type (Short
, Int
, Long
), then the division result is always an integer number (the fractional part is just dropped), so, if you have a val i: Int = 2
then i % 3 == 1
but i / 3 == 0
. To use fractional division, make at least one of the operands fractional like i / 3.0
or i.toDouble / 3
.
如果要检查Double
是否完整,可以使用d % 1.0 == 0.0
或检查Math.floor(d) == d
.
In case you want to check that a Double
is whole, you can use d % 1.0 == 0.0
or check that Math.floor(d) == d
.
这篇关于检查计算的输出是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!