【发布时间】:2019-07-10 06:46:38
【问题描述】:
我创建了一个函数,可以从用户的输入中找到越来越小的最接近的元素。
为了解决这个问题,我使用了.last() 和.first() 方法。
func closestNumbers(_ column: [String], value: Int) {
// Gets the closest element in array to userInput
let userInput = value
let rangeA = column
let left = rangeA.last(where: { $0 <= String(userInput)})! // last element that is less or equal to userInput
let right = rangeA.first(where: { $0 >= String(userInput)})! // first element that is bigger or the same as userInput
print(left, userInput, right)
// prints left <= userInput >= right
}
示例:如果 userInput 在 [100, 200, .... , 1000] 的数组中为 450。
打印应该返回 (400, 450, 500)
但是,它返回 1000、450、500。
虽然我觉得逻辑是对的。
【问题讨论】:
-
没错。就
String而言,"1000"小于"400"。只需比较整数 -
为什么你把你的号码投到
String,你应该把它们投到Int或Double。编辑:正如@vadian 所说,这很可能是由于这个演员表 -
我怀疑,谢谢我试试看!