【问题标题】:Swift ^ Operation on DoubleSwift ^ 双重操作
【发布时间】:2020-05-12 14:16:10
【问题描述】:

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

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

错误:二元运算符“^”不能应用于两个“双”操作数

以下是我的代码:

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


    【解决方案1】:

    ^bitwise XOR operator,而不是求幂。

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

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

    【讨论】:

      【解决方案2】:

      尝试使用 boucle For

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-10
        • 1970-01-01
        • 2015-07-11
        • 1970-01-01
        • 1970-01-01
        • 2013-06-04
        • 2023-03-27
        • 1970-01-01
        相关资源
        最近更新 更多