zoukankan      html  css  js  c++  java
  • 取余运算

    关于取余运算

    两个数 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));
    
    
    
    
    
  • 相关阅读:
    MySQL用户管理
    MySQL函数
    MySQL数据类型
    MySQL配置
    PowerDesigner之PDM检查
    PowerDesigner之PDM(物理概念模型)
    .NET Reflector反编译的方法
    IBatis.net 输出SQL语句(七)
    SVN 记录冲突、忽略
    SQLServer 窗口函数
  • 原文地址:https://www.cnblogs.com/daihanlong/p/11253552.html
Copyright © 2011-2022 走看看