了解模运算符的结果:%% [英] Understanding the result of modulo operator: %%

查看:151
本文介绍了了解模运算符的结果:%%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找适用于R语言中%%运算符的方法.

I'm looking for the methodology which applied to %% operator in R language.

10 %% 10  # 0
20 %% 10  # 0

怀疑这两个结果:

10 %% 20  # 10
2 %% 8  # 2

您能帮我更好地了解最后两个结果吗?我有点困惑.

Can you help me to understand better on the last two results? I'm little confused.

推荐答案

没有问题:

10 = 1 * 10 + 0
20 = 2 * 10 + 0
10 = 0 * 20 + 10
2  = 0 * 8  + 2 

模数是+之后的数字.

通常,对于两个数字ab,有

In general, for two numbers a and b, there is

a = floor(a / b) * b + (a %% b)

让我们编写一个玩具函数:

Let's write a toy function:

foo <- function(a,b) c(quotient = floor(a / b), modulo = a %% b)

foo(10, 10)
#quotient   modulo 
#   1        0 

foo(20, 10)
#quotient   modulo 
#   2        0 

foo(10, 20)
#quotient   modulo 
#   0       10 

foo(2, 8)
#quotient   modulo 
#   0        2 


更新:我们也可以使用a %/% b,而不是使用floor(a / b)来获得商.


Update: Instead of using floor(a / b) to get quotient, we can also use a %/% b.

这篇关于了解模运算符的结果:%%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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