-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))
1
  • What is the question? Please consider removing the C++ part. Commented Feb 21, 2018 at 21:33

1 Answer 1

1

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)")
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.