swift - 使用 Dictionary Swift 的 Repeat-While 循环
问题描述
我试图让这个循环正确运行,但它不会继续。如果用户没有输入与字典匹配的值,我需要它向下舍入到最接近的匹配,然后打印该值。
let dict = FitnessScore.powerThrow
var input = 19.30
var correctInput = false
func checkKey(score: Double) -> Bool {
for (key, _) in dict {
if key == input {
correctInput = true
return true
}
}
return false
}
func getFinnalInput() -> Double {
repeat {
input -= 0.1
checkKey(score: input)
print("this is the new input value: \(input)")
print("thie is the new condition: \(checkKey(score: input))")
return input
} while correctInput == true
}
print("your input score rounded down to \(getFinnalInput())")
struct FitnessScore {
static let powerThrow = [
12.50: 100,
12.40: 99,
12.20: 98,
12.10: 97,
11.90: 96,
11.80: 95,
11.60: 94,
11.50: 93,
11.30: 92,
11.20: 91,
11.00: 90,
10.90: 89,
10.70: 88,
10.60: 87,
10.40: 86,
10.30: 85,
10.10: 84,
10.00: 83,
9.80: 82 ]
}
解决方案
let userEntered = "12.9"
var input = Float(userEntered) ?? 0.0
func checkKey(score: Float) -> Bool {
let dict = FitnessScore.powerThrow
for (key, _) in dict {
if key == score {
return true
}
}
return false
}
func getFinnalInput() -> Float {
if checkKey(score: input) {
return input
} else {
repeat {
input -= 0.1
input = roundf(input * 100) / 100
print("this is the new input value: \(input)")
print("thie is the new condition: \(checkKey(score: input))")
checkKey(score: input)
} while checkKey(score: input) == false
return input
}
}
print("your input score rounded down to \(getFinnalInput())")
推荐阅读
- python - 如何获得张量值
- python - 将两个数组相乘得到矩阵
- rust - 参数要求为“静态”借用值不适用于非复制值
- xslt - XSLT | 使用标识符对 XSLT 进行分组 | 添加该组中的所有元素
- java - 在java8 steam中从map的键中附加一个匹配值的字符串
- html - 使用 flexbox 垂直居中不会将文本传递到彼此下方
- humhub - 如何在 Humhub 模块上显示“设置为默认”菜单?
- php - 如果用户已登录,则显示两个价格。将可变价格更改为 from。显示可变产品的自定义价格变化
- python - 如何在内存中从数据帧转换为 TextIOWrapper?
- sql - 我在 STU_GPA 行或附近不断收到错误。我不明白问题是什么