Swift ^ Double 运算
Swift ^ Operation on Double
我正在尝试解决一个难题,但代码总是失败。
我需要对双打执行 ^ 操作。挑战是如果我调用一个函数 calculate(3,2,^) 那么我应该得到结果 9.
我尝试了以下代码但失败并出现此错误:
error: binary operator '^' cannot be applied to two 'Double' operands
下面是我的代码:
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
}
尝试使用 boucle For
for (let index = 0; index < b; index++) {
c= a*index;
}
^
是bitwise XOR operator,不是求幂。
改用pow(_:_:)
方法:
else if op == "^"
{
c = pow(a, b)
}
我正在尝试解决一个难题,但代码总是失败。 我需要对双打执行 ^ 操作。挑战是如果我调用一个函数 calculate(3,2,^) 那么我应该得到结果 9.
我尝试了以下代码但失败并出现此错误:
error: binary operator '^' cannot be applied to two 'Double' operands
下面是我的代码:
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
}
尝试使用 boucle For
for (let index = 0; index < b; index++) {
c= a*index;
}
^
是bitwise XOR operator,不是求幂。
改用pow(_:_:)
方法:
else if op == "^"
{
c = pow(a, b)
}