取余运算

关于取余运算

两个数 n d 进行取余,记为: n % d (d !== 0).
对于结果 r 的正负性,可以规定为,与 n 的符号一致.
见下面的mod函数.

console.log('-12%5:',-12%5);
console.log('12%-5:',12%-5);
console.log('7%-3:',7%-3);
// console.log('3%0',3%0);
console.log('-12%-5',-12%-5);

function _pos_mod(n,d) {
    if(n < 0 || d < 0){
        throw new Error(`n:${n} or d:${d} 应该 >= 0`);
    }
    if(d === 0){
        throw new Error('不能对0取余');
    }
    if(n < d){
        return n;
    }
    return _pos_mod(n - d,d);
}

function abs(x){
    if(x >= 0){
        return x;
    }
    return -x;
}

function mod(n,d){
    // 正数取余 结果 >= 0 
    // 负数取余 结果 <= 0
    // 正负取余 结果 >= 0
    // 负正取余 结果 <= 0
    // 正负性 取决于第一个数
    if(n >= 0){
        return _pos_mod(n,abs(d));
    }else{
        return -_pos_mod(abs(n),abs(d));
    }
}

console.log('-------------');
console.log('-12%5:',mod(-12,5));
console.log('12%-5:',mod(12,-5));
console.log('7%-3:',mod(7,-3));
// console.log('3%0',3%0);
console.log('-12%-5',mod(-12,-5));



转载于:https://www.cnblogs.com/daihanlong/p/11253552.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值