如何快速显示多个双打和字符串?

时间:2018-10-26 19:27:42

标签: ios swift

我正在制作IOS余数计算器。

我已经弄清楚了所有内容,并为除法运算符 的所有运算工作,我想显示商和余数。

我需要显示商,显示余数的字符串和实际余数。

像这样:

9/5 =

1 R. 4

如果有人可以帮助我,将不胜感激

3 个答案:

答案 0 :(得分:4)

尝试一下

let result = Int(a/b)
let remainder = a % b
let resultedString = "\(result) R \(remainder)"

答案 1 :(得分:2)

当除数为负时,使用模数%来得到整数除法的余数是一个常见错误。这是扩展Euclidean division的正确实现,可以保证余数为正且严格小于除数

func euclideanDivision(dividend: Int, divisor: Int) -> (quotient: Int, remainder: Int) {
    guard divisor != 0 else {
        fatalError("The divisor shouldn't be zero")
    }

    var q = dividend / divisor
    if q * divisor > dividend {
        q += q.signum()
    }
    let r = dividend - (divisor * q)

    return (quotient: q, remainder: r)
}

signum()如果为正,则返回1,如果为负,则返回-1。

以下是一些测试用例:

print(euclideanDivision(dividend: 7, divisor: 3))    //(quotient: 2, remainder: 1)
print(euclideanDivision(dividend: 7, divisor: -3))   //(quotient: -2, remainder: 1)
print(euclideanDivision(dividend: -7, divisor: 3))   //(quotient: -3, remainder: 2)
print(euclideanDivision(dividend: -7, divisor: -3))  //(quotient: 3, remainder: 2)
print(euclideanDivision(dividend: 0, divisor: -3))   //(quotient: 0, remainder: 0)
print(euclideanDivision(dividend: 1, divisor: 3))   //(quotient: 0, remainder: 1)
print(euclideanDivision(dividend: -1, divisor: 3))  //(quotient: 0, remainder: -1)
print(euclideanDivision(dividend: 1, divisor: -3))   //(quotient: 0, remainder: 1)
print(euclideanDivision(dividend: -1, divisor: -3))  //(quotient: 0, remainder: -1)
euclideanDivision(dividend: -7, divisor: 0)          //Fatal error: The divisor shouldn't be zero

您可以将结果格式化为字符串:

let division = euclideanDivision(dividend: 9, divisor: 5)
let quotient = division.quotient
let remainder = division.remainder

print(String(quotient) + " R. " + String(remainder))   //"1 R. 4"

答案 2 :(得分:0)

FYYI:快速的方式

    let result = 9.quotientAndRemainder(dividingBy: 5)
    print (  "\(result.quotient) R. \(result.remainder)")