你们中有人知道如何检查除法余数是整数还是零吗?
if ( integer ( 3/2))
你应该像这样使用模运算符
// a,b are ints
if ( a % b == 0) {
// remainder 0
} else
{
// b does not divide a evenly
}
听起来你需要的是取模运算符%
,它会给出一个操作的余数。
3 % 2 // yields 1
3 % 1 // yields 0
3 % 4 // yields 1
然而,如果你想先执行除法运算,你可能需要更复杂的方法,例如以下内容:
//Perform the division, then take the remainder modulo 1, which will
//yield any decimal values, which then you can compare to 0 to determine if it is
//an integer
if((a / b) % 1 > 0))
{
//All non-integer values go here
}
else
{
//All integer values go here
}
详细指南
(3 / 2) // yields 1.5
1.5 % 1 // yields 0.5
0.5 > 0 // true
var val = 3/2
var integerType = Mirror(reflecting: val)
if integerType.subjectType == Int.self {
print("Yes, the value is an integer")
}else{
print("No, the value is not an integer")
}
如果上面的内容有用,请让我知道。
Swift 5
if numberOne.isMultiple(of: numberTwo) { ... }
Swift 4或更早版本
if numberOne % numberTwo == 0 { ... }
Swift 3:
if a.truncatingRemainder(dividingBy: b) == 0 {
//All integer values go here
}else{
//All non-integer values go here
}
Swift 2.0
print(Int(Float(9) % Float(4))) // result 1
%
取模运算,可以得到余数。 - nhahtdh