Reputation: 21
I am trying to solve a challenge but the code keeps failing. I need to perform a ^ operation on doubles. Challenge was if I call a function calculate(3,2,^) then I should get the result 9.
I tried the below code but failed with this error:
error: binary operator '^' cannot be applied to two 'Double' operands
Below is my Code:
func calc(a: Double, b: Double, op: Character) -> Double {
var c:Double
c = 0
if op == "+"
{
c = a + b
}
else if op == "-"
{
c = a - b
}
else if op == "*"
{
c = a * b
}
else if op == "/"
{
c = a / b
}
else if op == "%"
{
let rem = a.truncatingRemainder(dividingBy: b)
c = rem
}
else if op == "^"
{
let z = a ^ b
c = z
}
return c
}
Upvotes: 1
Views: 515
Reputation: 9829
^
is the bitwise XOR operator, not exponentiation.
Use the pow(_:_:)
method instead:
else if op == "^"
{
c = pow(a, b)
}
Upvotes: 6
Reputation: 1
try to use boucle For
for (let index = 0; index < b; index++) {
c= a*index;
}
Upvotes: -1