swift中的负数模数 [英] Negative number modulo in swift

查看:346
本文介绍了swift中的负数模数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

负数的模数如何在swift中工作?
当我做(-1%3)时,它给出-1但余数为2.它有什么收获?

How does modulo of negative numbers work in swift ? When i did (-1 % 3) it is giving -1 but the remainder is 2. What is the catch in it?

推荐答案

Swift 余数运算符 计算整数除法的
的余数:

The Swift remainder operator % computes the remainder of the integer division:

a % b = a - (a/b) * b

其中 / 是截断整数除法。在您的情况下

where / is the truncating integer division. In your case

(-1) % 3 = (-1) - ((-1)/3) * 3 = (-1) - 0 * 3 = -1

因此余数总是与股息(除非
剩余部分为零)。

So the remainder has always the same sign as the dividend (unless the remainder is zero).

这与所需的定义相同,例如在C99标准中,
参见例如
ANSI C或ISO C是否指定-5%10应该是什么?。另请参阅
维基百科:Modulo操作,了解概述
如何处理用不同的编程语言。

This is the same definition as required e.g. in the C99 standard, see for example Does either ANSI C or ISO C specify what -5 % 10 should be?. See also Wikipedia: Modulo operation for an overview how this is handled in different programming languages.

可以在Swift中定义真正的模数函数,如下所示:

A "true" modulus function could be defined in Swift like this:

func mod(_ a: Int, _ n: Int) -> Int {
    precondition(n > 0, "modulus must be positive")
    let r = a % n
    return r >= 0 ? r : r + n
}

print(mod(-1, 3)) // 2

这篇关于swift中的负数模数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆