-1

I recently started learning both C++ and Swift. I've already written a few programs in C++ and decided to try translating one of them into Swift. I have run into an issue though. When I try to get input from the user in Swift using readline(), it saves the numbers as a string and not a Double. As a result I get errors later in my program whenever I try to calculate.

Binary operator '*' cannot be applied to operands of type 'Double' and 'String'

I've tried searching the Internet for a way to correct this but all the instructions I've found are outdated. If anybody could help it would be greatly appreciated.

Below is my attempt to translate the C++ code into 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))
rmaddy
  • 298,130
  • 40
  • 468
  • 517

1 Answers1

0

readLine(strippingNewline:) returns an object of type String. Thus you have to try casting from String to double. Your program then becomes :

//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)")
michael-martinez
  • 526
  • 3
  • 18