我最近开始学习C ++和Swift。我已经用C ++编写了一些程序,并决定尝试将其中一个程序翻译成Swift。我遇到了一个问题。当我尝试使用readline()
从Swift中的用户获取输入时,它将数字保存为字符串而不是Double。因此,每当我尝试计算时,我的程序中都会出现错误。
二进制运算符'*'不能应用于'Double'和'String'
类型的操作数
我已经尝试在互联网上搜索纠正此问题的方法,但我发现的所有说明都已过时。如果有人能提供帮助,我们将不胜感激。
以下是我尝试将C ++代码翻译成Swift。
/* Calculate and display the circumference of a circular gazebo and the price of the railing materials for it. */
import Foundation
//Declare Name Constants
let PI : Double = 3.141593
//Input
print("Enter the diameter (in feet) of the gazebo: ")
let gazeboDiameter = (readLine()!)
print ("Enter the price (per foot) of railing material: ")
let priceOfRailing = ((readLine()!)
// Calculate circumference and price
let circumference = PI * gazeboDiameter
let costOfGazebo = circumference * priceOfRailing
//Output
print("The Diameter of the Gazebo is: " (gazeboDiameter))
print("The price (per foot) of the railing material is: "(costOfGazebo))
print("The circumference of the gazebo is: " (circumference))
print("The price of the railing will be: $"(costOfGazebo))
答案 0 :(得分:0)
readLine(strippingNewline :)返回String类型的对象。 因此,您必须尝试从String转换为double。 然后你的程序变成:
//SWIFT
/* Calculate and display the circumference of a circular gazebo and the price of the railing materials for it. */
import Foundation
//Declare Variables
var gazeboDiameter: Double = 0.0
var priceOfRailing: Double = 0.0
var circumference: Double = 0.0
var costOfGazebo: Double = 0.0
//Input
print("Enter the diameter (in feet) of the gazebo: ")
gazeboDiameter = Double(readLine()!)!
print ("Enter the price (per foot) of railing material: ")
priceOfRailing = Double(readLine()!)!
// Calculate circumference and price
circumference = Double.pi * gazeboDiameter
costOfGazebo = circumference * priceOfRailing
//Output
print("The Diameter of the Gazebo is: \(gazeboDiameter)")
print("The price (per foot) of the railing material is: \(costOfGazebo)")
print("The circumference of the gazebo is: \(circumference)")
print("The price of the railing will be: $\(costOfGazebo)")