我正在Swift Playgrounds应用程序中进行测验,我想保留一个正确答案数量的计数器.价值correct不会改变,我不知道为什么.
var correct:Int = 0
func qa(question: String, answer: String) {
show(question)
var ans = ask("answer")
if (ans.lowercased() == answer) {
show("correct")
correct = correct + 1
} else {
show("wrong you numpty!")
}
}
func qaor(question: String, answer: String, answer2: String) {
show(question)
var ans = ask("answer")
if (ans.lowercased() == answer) || (ans.lowercased() == answer2) {
show("correct")
correct = correct + 1
} else {
show("wrong you numpty!")
}
}
show("What is your name?")
let name = ask("Name")
show("Hi " + name)
qa(question: "What is the name of the character played by Simon Jones in the Hitchikers Guide to the Galaxy?", answer: "arthur dent")
qaor(question: "What is voiced by Peter Jones in the Hitchikers Guide to the Galaxy?", answer: "the book", answer2: "the guide")
qa(question: "finish this sentence .doing the coastlines was always my Favourite, the rough crinkley edges, .... ", answer: "fjords")
var cf = "no"
if (correct == 0) {
var cf = "no"
} else if (correct == 1) {
var cf = "one"
} else if (correct == 2) {
var cf = "two"
} else if (correct == 3) {
var cf = "three"
}
show("you got " + cf + " questions correct out of three")
Run Code Online (Sandbox Code Playgroud)
不要cf为每个if/else语句声明变量.它会创建一个局部变量,而您不会更改第一个变量cf.
相反,试试这个:
var cf = "no"
if (correct == 0) {
cf = "no"
} else if (correct == 1) {
cf = "one"
} else if (correct == 2) {
cf = "two"
} else if (correct == 3) {
cf = "three"
}
show("you got " + cf + " questions correct out of three")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |