从stackoverflow上的Simple C程序开始,我在Swift中再次完成了这个代码:
import Foundation
// variables and constants:
var dice1, dice2: UInt32
var score, scoreToWin, diceSum: Int
dice1 = 0
dice2 = 0
diceSum = 0
// functions:
func rollDice() ->Int {
dice1 = arc4random() % 6 + 1
dice2 = arc4random() % 6 + 1
diceSum = Int(dice1 + dice2)
println("\(diceSum)")
return diceSum
}
// main:
score = rollDice()
println("\(dice1) \(dice2) \(score)")
switch score {
case 7, 11:
println("score=\(score)\nYou WIN")
case 2, 3, 12:
println("score=\(score)\nYou LOOSE")
default:
println("You have to roll a \(score) to WIN")
do {
scoreToWin = score
diceSum = rollDice()
if diceSum == 7 { println("You LOOSE") }
else if diceSum == scoreToWin { println("You WIN") }
} while (diceSum != scoreToWin && diceSum != 7)
}
Run Code Online (Sandbox Code Playgroud)
这是一个可能的输出:
我没想到第一行输出,因为第一行表示函数rollDice()在定义时运行.如何在不实际运行的情况下定义函数?
score = rollDice()6因为println("\(diceSum)")你在rollDice方法中所做的事情会打印你正在看到的.
声明方法不会运行它.不是快速的,也不是我能想到的任何其他语言.
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |