如何在 Swift 程序中从标准输入读取数字?
本教程将讨论如何编写一个 Swift 程序,从标准输入读取数字。借助 readLine()、Int() 和 Float() 函数,在 Swift 中从标准输入读取数字非常容易。
readLine() 函数 - 此函数返回一个字符串,该字符串是从当前行的末尾从标准输入读取的。如果在调用 readLine() 函数时控制权已到达 EOF,则此方法将返回 nil。
语法
以下是 Swift readLine() 函数的语法:
readLine(strippingNewline: true) Or readLine()
Int() 函数 - 此函数用于将字符串转换为带符号的整数值类型。整数的大小取决于平台,这意味着如果平台是 32 位,则大小为 Int32。
语法
以下是 Swift Int() 函数的语法:
Int()
Float() 函数 - 此函数用于将字符串转换为单精度浮点值类型。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
语法
以下是 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