我对Swift很新,这让我很难过。我有:
for values in input {
if num >= 80 {
message = "hot!"
}
else if num >= 60 && num < 80 {
message = "warm!"
}
else if num >= 40 && num < 60 {
message = "cool!"
}
else if num <= 40 {
message = "cold!"
}
print("The temperature \(values) is \(message)")
}
这是打印为
"Please enter a temperature 65"
"Please enter a temperature 1"
"Please enter a temperature 100"
"Please enter a temperature 56"
"Please enter a temperature 46"
"The temperature 65 is warm!"
"The temperature 1 is warm!"
"The temperature 100 is warm!"
"The temperature 56 is warm!"
"The temperature 46 is warm!"
正如你所看到的那样,它不是一个一个地去,而是命名数组的每个元素相同。我在这做错了什么?我正在使用readLine()作为数组元素。
答案 0 :(得分:1)
由于您正在学习Swift,因此您需要学习几个约定:
inputs
而不是input
。value
而不是values
。value
而不是num
除此之外,您可以使用switch
更简洁地编写代码:
for value in inputs {
var message = ""
switch value {
case 80...: // equivalent to: if 80 <= num
message = "hot!"
case 60..<80: // equivalent to: if 60 <= num && num < 80
message = "warm!"
case 40..<60: // equivalent to: if 40 <= num && num < 60
message = "cool"
case ..<40: // equivalent to: if num < 40
message = "cold"
default:
message = "" // this is actually not reachable since the cases above cover
// all possible scenarios. But Swift require switch statement
// to be exhaustive and it doesn't go that deep to prove that
// we already had everything covered. This is to silence the
// compiler.
}
print("The temperature \(value) is \(message)")
}
答案 1 :(得分:0)
在for循环中,您将num与您的临时范围进行比较,而不是值变量。所以我相信num的值已经在数组本身之外定义,并且从未发生变异。
话虽如此,我相信一个转换声明会更适合你的需求,在这种情况下会更清晰。
不要忘记比较值而不是num变量
答案 2 :(得分:0)
您可以这样使用:
for value in input {
if value >= 80 {
message = "hot!"
}
else if value >= 60 && value < 80 {
message = "warm!"
}
else if value >= 40 && value < 60 {
message = "cool!"
}
else if value <= 40 {
message = "cold!"
}
print("The temperature \(value) is \(message)")
}