Why can't I divide integers in swift?
The OP seems to know how the code has to look like but he is explicitly asking why it is not working the other way.
So, "explicitly" is part of the answer he is looking for: Apple writes inside the "Language Guide" in chapter "The Basics" -> "Integer and Floating-Point Conversion":
Conversions between integer and floating-point numeric types must be
made explicit
Divided operation in Swift
Swift has strict rules about the whitespace around operators. Divide '/' is a binary operator.
The important rules are:
- If an operator has whitespace around both sides or around neither
side, it is treated as a binary operator. As an example, the +
operator in a+b and a + b is treated as a binary operator.- If an operator has whitespace on the left side only, it is treated as a
prefix unary operator. As an example, the ++ operator in a ++b is
treated as a prefix unary operator.- If an operator has whitespace on
the right side only, it is treated as a postfix unary operator. As an
example, the ++ operator in a++ b is treated as a postfix unary
operator.
That means that you need to add a space before the /
or remove the space after it to indicate that it is a binary operator:
var rotation = Double(arc4random_uniform(50)) / (100.0 - 0.2)
If you want rotation
to be a Float, you should use that instead of Double:
var rotation = Float(arc4random_uniform(50)) / (100.0 - 0.2)
There is no need to specify the type explicitly since it will be inferred from the value you are assigning to. Also, you do not need to explicitly construct your literals as a specific type as those will conform to the type you are using them with.
Divide two numbers and return fraction in swift
To get the quotient and remainder of a division, you can use the quotientAndRemainder(dividingBy:)
function.
3.quotientAndRemainder(dividingBy: 6) // (quotient 0, remainder 3)
If you want to get the floating point result of a division, use the /
operator on two floating point numbers.
Either do
let result = 3.0 / 6.0 // 0.5
or if your integers are coming from variables, do
let result = Double(3.0) / Double(6.0) // 0.5
Is the Swift divide / operator not working or have I missed something?
Your problem is here: 1/36
. Both 1 and 36 are Int
s. Try this:
var probabilitiesX = Array(repeating: 1.0 / 36.0, count: 36)
How to divide two numbers in swift using two variables?
Division operator is
/
, not\
.sum\numbers
- um, what? Did you meansum / numbers.count
?
Float divison and casting in Swift
First, you should use Double and not Float. Float gives you very limited precision. Why you would want 6 digits precision with Float when you could have 15 digits with Double is hard to understand.
Second, a compiler does exactly what you tell it.
Float (sum) / Float (numbers.count)
takes the integer "sum", takes the integer "numbers.count", converts both to Float and divides. Divison of Float gives a result in this case of 3.5.
Float (sum/numbers.count)
divides the integer "sum" by the integer "numbers.count". Division of integers gives an integer result, which is the integer quotient disregarding any remainder. 21 / 6 equals 3 with a remainder of 3. So the result of the division is 3, which you then convert to the Float 3.0.
Mathematical operations on CGPoint in Swift
It is not strictly meaningful to add two CGPoints. It's not completely wrong; it's just not meaningful because points are coordinates, not offsets. "Chicago + New York" is not a new location.
Generally you would offset a CGPoint using a CGVector, CGSize/NSSize, or a UIOffset. Those also don't have a +
operator, but it would make more sense to add the operator to CGPoint+CGVector rather than two CGPoints.
But you're free to add it the way you did if it's particularly convenient.
How to execute multiplications and/or divisions in the right order?
If you only have the four operations +
, -
, x
, and ÷
, you can do this by keeping track of a pendingOperand
and pendingOperation
whenever you encounter a +
or -
.
Then compute the pending operation when you encounter another +
or -
, or at the end of the calculation. Note that +
or -
computes the pending operation, but then immediately starts a new one.
I have modified your function to take the stringNumbers
, operators
, and initial
values as input so that it could be tested independently in a Playground.
func calculateTotal(stringNumbers: [String], operators: [String], initial: Double) -> Double {
func performPendingOperation(operand: Double, operation: String, total: Double) -> Double {
switch operation {
case "+":
return operand + total
case "-":
return operand - total
default:
return total
}
}
var total = initial
var pendingOperand = 0.0
var pendingOperation = ""
for (i, stringNumber) in stringNumbers.enumerated() {
if let number = Double(stringNumber) {
switch operators[i] {
case "+":
total = performPendingOperation(operand: pendingOperand, operation: pendingOperation, total: total)
pendingOperand = total
pendingOperation = "+"
total = number
case "-":
total = performPendingOperation(operand: pendingOperand, operation: pendingOperation, total: total)
pendingOperand = total
pendingOperation = "-"
total = number
case "÷":
total /= number
case "×":
total *= number
default:
break
}
}
}
// Perform final pending operation if needed
total = performPendingOperation(operand: pendingOperand, operation: pendingOperation, total: total)
// clear()
return total
}
Tests:
// 4 + 3
calculateTotal(stringNumbers: ["3"], operators: ["+"], initial: 4)
7
// 4 × 3
calculateTotal(stringNumbers: ["3"], operators: ["×"], initial: 4)
12
// 2 + 2 × 4
calculateTotal(stringNumbers: ["2", "4"], operators: ["+", "×"], initial: 2)
10
// 2 × 2 + 4
calculateTotal(stringNumbers: ["2", "4"], operators: ["×", "+"], initial: 2)
8
// 17 - 2 × 3 + 10 + 7 ÷ 7
calculateTotal(stringNumbers: ["2", "3", "10", "7", "7"], operators: ["-", "×", "+", "+", "÷"], initial: 17)
22
Related Topics
How to Center Align the Cells of a Uicollectionview
How to I Import 3Rd Party Frameworks into Xcode Playground
Real Time Blur Effect for Navigation Bar
How to Add Images for Different Screen Size from Assets.Xcassets in Xcode 8
Alamofire Invalid Value Around Character 0
Nsurlconnection Get Request Returns -1005, "The Network Connection Was Lost"
Storing Asynchronous Cloud Firestore Query Results in Swift
Tweening/Interpolating Between Two Cgpaths/Uibeziers
Change Default Icon for Moving Cells in Uitableview
Reading the Gps Data from the Image Returned by the Camera in iOS Iphone
How to Store an Image in Core Data
Differencebetween Pan and Swipe in iOS
How to Implement Auto-Complete for Address Using Apple Map Kit
Optional Binding with Try? and As? Still Produces an Optional Type
How to Get iOS Device MAC Address Programmatically
How to Put the Image on the Right Side of the Text in a Uibutton