我有一個搜索格式爲[(Double,Double)]的元組的函數。它找到給定的x值,如果找到,則返回相應的y值。如何在數組中使用限制位數來搜索數組?
我需要改變它,以便不是在(x,y)對列表中搜索確切的x值,而是隻搜索給定搜索項的小數點後的相同位數。
實施例:
var a: [(Double, Double)] = [(0.0,0.0)]
a = [(0.1234, 0.0), (0.12345, 1.0), (0.123456, 2.0), (0.1234567, 3.0)]
//the current version of the function, this is what I need to change
func getValueFromTuples(tupleArr:[(Double,Double)],n:Double)->Double?{
for tuple in tupleArr{
if tuple.0 == n{
return tuple.1
}
}
return nil
}
print("Value:", getValueFromTuples(tupleArr: a, n: 0.1234)!)
//needs to return 0.0
print("Value:", getValueFromTuples(tupleArr: a, n: 0.12345)!)
//needs to return 1.0
print("Value:", getValueFromTuples(tupleArr: a, n: 0.123456)!)
//needs to return 2.0
您對發佈的代碼有什麼問題? – rmaddy
問題是,如果我搜索值「0.12」,則不返回任何內容。這是因爲'0.12'不在數組中。所以我需要函數將數組中的x值截斷爲與輸入項相同的小數位數。所以每個x值將被截斷爲0.12,然後我只需要返回匹配的第一個y值。 – loltospoon
不相關,但你爲什麼不使用像CGCON這樣更方便的類型? – vadian