编程基础/条件示例 Swift
外观
< 编程基础
// This program asks the user for a Fahrenheit temperature,
// converts the given temperature to Celsius,
// and displays the results.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
func getChoice() -> String {
var choice: String
print("Enter C to convert to Celsius or F to convert to Fahrenheit:")
choice = readLine(strippingNewline: true)!
return choice
}
func getTemperature(label: String) -> Double {
var temperature: Double
print("Enter " + label + " temperature:")
temperature = Double(readLine(strippingNewline: true)!)!
return temperature
}
func calculateCelsius(fahrenheit: Double) -> Double {
var celsius: Double
celsius = (fahrenheit - 32) * 5 / 9
return celsius
}
func calculateFahrenheit(celsius: Double) -> Double {
var fahrenheit: Double
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
}
func displayResult(temperature: Double, fromLabel: String, result: Double, toLabel: String) {
print(String(temperature) + "° " + fromLabel + " is " + String(result) + "° " + toLabel)
}
func main() {
// main could either be an if-else structure or a switch-case structure
var choice: String
var temperature: Double
var result: Double
choice = getChoice()
// if-else approach
if choice == "C" || choice == "c" {
temperature = getTemperature(label:"Fahrenheit")
result = calculateCelsius(fahrenheit:temperature)
displayResult(temperature:temperature, fromLabel:"Fahrenheit", result:result, toLabel:"Celsius") }
else if choice == "F" || choice == "f" {
temperature = getTemperature(label:"Celsius")
result = calculateFahrenheit(celsius:temperature)
displayResult(temperature:temperature, fromLabel:"Celsius", result:result, toLabel:"Fahrenheit")
}
else {
print("You must enter C to convert to Celsius or F to convert to Fahrenheit.")
}
// switch-case approach
switch choice {
case "C", "c":
temperature = getTemperature(label:"Fahrenheit")
result = calculateCelsius(fahrenheit:temperature)
displayResult(temperature:temperature, fromLabel:"Fahrenheit", result:result, toLabel:"Celsius")
case "F", "f":
temperature = getTemperature(label:"Celsius")
result = calculateFahrenheit(celsius:temperature)
displayResult(temperature:temperature, fromLabel:"Celsius", result:result, toLabel:"Fahrenheit")
default:
print("You must enter C to convert to Celsius or F to convert to Fahrenheit.")
}
}
main()
Enter C to convert to Celsius or F to convert to Fahrenheit: c Enter Fahrenheit temperature: 100 100.0° Fahrenheit is 37.77777777777778° Celsius Enter C to convert to Celsius or F to convert to Fahrenheit: f Enter Celsius temperature: 100 100.0° Celsius is 212.0° Fahrenheit Enter C to convert to Celsius or F to convert to Fahrenheit: x You must enter C to convert to Celsius or F to convert to Fahrenheit.