如何在 Swift 程式中從標準輸入讀取數字?
本教程將討論如何編寫一個 Swift 程式,從標準輸入讀取數字。藉助 readLine()、Int() 和 Float() 函式,在 Swift 中從標準輸入讀取數字非常容易。
readLine() 函式 - 此函式返回一個字串,該字串是從當前行的末尾從標準輸入讀取的。如果在呼叫 readLine() 函式時控制權已到達 EOF,則此方法將返回 nil。
語法
以下是 Swift readLine() 函式的語法:
readLine(strippingNewline: true) Or readLine()
Int() 函式 - 此函式用於將字串轉換為帶符號的整數值型別。整數的大小取決於平臺,這意味著如果平臺是 32 位,則大小為 Int32。
語法
以下是 Swift Int() 函式的語法:
Int()
Float() 函式 - 此函式用於將字串轉換為單精度浮點值型別。
語法
以下是 Swift Float() 函式的語法:
Float()
從使用者獲取輸入的演算法
步驟 1 - 定義一個變數
步驟 2 - 使用 readline() 語法將輸入值儲存在上述變數中
步驟 3 - 列印該變數
步驟 4 - 使用該變數執行各種操作
步驟 5 - 列印輸出
示例
從標準輸入讀取整數型別數字
以下 Swift 程式將展示如何使用 readLine() 和 Int() 函式從標準輸入讀取整數型別數字。這裡我們首先使用 readLine() 函式從使用者處讀取圓的半徑作為輸入,然後使用 Int() 函式將該字串型別輸入轉換為整數型別。之後我們計算圓的面積。
import Foundation
import Glibc
print("Please enter the radius(r) of the circle:")
if let readValue = readLine() {
if let radius = Int(readValue) {
let area = (22 * radius * radius)/7
print("Hence the area of the circle:", area)
}
}輸入
Please enter the radius(r) of the circle: 20
輸出
Hence the area of the circle: 1257
在上面的程式碼中,我們首先使用 readLine() 函式讀取使用者的半徑(即 20)並將其分配給一個變數。readLine() 函式以字串格式讀取資料,因此我們使用 Int() 函式將半徑轉換為整數。讀取半徑後,我們使用以下程式碼計算圓的面積
let area = (22 * radius * radius)/7
並在輸出螢幕上顯示圓的面積,即 1257。
示例
從標準輸入讀取浮點型別數字
以下 Swift 程式將展示如何使用 readLine() 和 Float() 函式從標準輸入讀取浮點型別數字。這裡我們首先使用 readLine() 函式從使用者處讀取圓的半徑作為輸入,然後使用 Float() 函式將該字串型別輸入轉換為浮點型別。之後我們計算圓的周長。
import Foundation
import Glibc
print("Please enter the radius(r) of the circle:")
if let readValue = readLine() {
if let radius = Float(readValue) {
let Circumference = 2 * 3.14 * radius
print("Hence the Circumference is:", Circumference)
}
}輸入
Please enter the radius(r) of the circle: 10
輸出
Hence the Circumference is: 62.800003
在上面的程式碼中,我們首先使用 readLine() 函式讀取使用者的半徑(即 10)並將其分配給一個變數。readLine() 函式以字串格式讀取資料,因此我們使用 Float() 函式將半徑轉換為浮點數。讀取半徑後,我們使用以下程式碼計算圓的周長
let Circumference = 2 * 3.14 * radius
並在輸出螢幕上顯示圓的周長,即 62.800003
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP