Swift ^ Double运算

问题描述 投票:0回答:3

我正在尝试解决挑战,但是代码不断失败。我需要对双打执行^操作。挑战是,如果我调用函数calculate(3,2,^),那么我应该得到结果9。

我尝试了下面的代码,但由于此错误而失败:

错误:二进制运算符'^'无法应用于两个'Double'操作数

下面是我的代码:

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
}
swift binary double calculator operation
3个回答
2
投票

[^bitwise XOR operator,不是幂。

改为使用pow(_:_:)方法:

else if op == "^"
{
    c = pow(a, b)
}

0
投票

尝试使用boucle用于

  for (let index = 0; index < b; index++) {
    c= a*index;

} 

0
投票

我假设您认为“ ^”的意思是“达到”的力量,因此在您的示例中,您试图使3获得“达到”的力量2使您得到9。

在编码中,“ ^”用于按位XOR运算,您不能真正将2 Doubles一起进行XOR!

© www.soinside.com 2019 - 2024. All rights reserved.