iOS如何检查除法余数是否为整数?

3

你们中有人知道如何检查除法余数是整数还是零吗?

if ( integer ( 3/2))

3
使用 % 取模运算,可以得到余数。 - nhahtdh
6个回答

27

你应该像这样使用模运算符

// a,b are ints
if ( a % b == 0) {
  // remainder 0
} else
{
  // b does not divide a evenly
}

2
我相信Juan正在尝试执行除法(包括任何小数余数),并确定该结果是否为整数。 - Rion Williams

3

听起来你需要的是取模运算符%,它会给出一个操作的余数。

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

我的问题是如何知道余数是否为整数或零。例如3/2,余数不是零或整数。 - Juan
我尝试了以下代码: if ((10%2)% 1 > 0) { NSLog( @"reminder of %d", (10/2) ); } 但是它没有起作用。 - Juan
1
@RionWilliams 那很聪明! - dasdom
@Juan,我对Xcode(或Objective-C)并不是非常熟悉,但我会为你进一步了解它。 - Rion Williams
@Juan,这可能与输出通过NSLog格式化小数的方式有关吗? - Rion Williams
(a / b)%1如果a和b是整数,则始终为0。1.5%1无法编译。 - Jesse Black

0
您可以使用以下代码来确定实例的类型。
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")
}

如果上面的内容有用,请让我知道。


0

Swift 5

if numberOne.isMultiple(of: numberTwo) { ... }

Swift 4或更早版本

if numberOne % numberTwo == 0 { ... }

0

Swift 3:

if a.truncatingRemainder(dividingBy: b) == 0 {
    //All integer values go here
}else{
    //All non-integer values go here
}

-1

Swift 2.0

print(Int(Float(9) % Float(4)))   // result 1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接