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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14129649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:41:53  来源:igfitidea点击:

ios how to check if division remainder is integer

iphoneiosxcodeipad

提问by Juan

any of you knows how can I check if the division remainder is integer or zero?

你们中的任何人都知道如何检查除法余数是整数还是零?

if ( integer ( 3/2))

回答by Jesse Black

You should use the modulo operator like this

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

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

回答by Rion Williams

It sounds like what you are looking for is the modulo operator %, which will give you the remainder of an operation.

听起来您正在寻找的是 modulo operator %,它将为您提供运算的其余部分。

3 % 2 // yields 1
3 % 1 // yields 0
3 % 4 // yields 1

However, if you want to actually perform the division first, you may need something a bit more complex, such as the following:

但是,如果您想先实际执行除法,则可能需要一些更复杂的内容,例如以下内容:

//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
}

Walkthrough

演练

(3 / 2) // yields 1.5
1.5 % 1 // yields 0.5
0.5 > 0 // true

回答by Hussein Dimessi

swift 3:

快速3:

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

回答by DILIP KOSURI

You can use the below code to know which type of instance it is.

您可以使用以下代码来了解它是哪种类型的实例。

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")
}

let me know if the above was useful.

如果以上有用,请告诉我。

回答by maxwell

Swift 5

斯威夫特 5

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

Swift 4 or less

Swift 4 或以下

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

回答by Programer_saeed

Swift 2.0

斯威夫特 2.0

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