C/C++求余运算符
C++求余运算符: a%b
双目运算符,两个操作数须是(或可转化为)整型的变量或字面值。
注意:
1. 如无特殊需求,两个操作数宜为带符号的整型变量;
2. 对于 int a,b; , a%b 等价于 a-a/b*b ;
3. 运算符可解释为: a%b 为将b乘以某个整数c,以使|b*c|尽量接近而不超过|a|,则a%b=a-b*c。
从而 a%b 的值保持了a的符号或为0。
例:
1 #include<iostream> 2 using namespace std; 3 int main(){ 4 int a=7, b=-7, c=3, d=-3; 5 unsigned ua=7, uc=3; 6 cout << "7/3=" << a/c << ";\t\t7%3=" << a%c << endl; 7 cout << "u7/u3=" << ua/uc << ";\tu7%u3=" << ua%uc <<"\t!!!" << endl;//!!! 8 cout << endl; 9 cout << "7/-3=" << a/d << ";\t7%-3=" << a%d << endl; 10 cout << "u7/-3=" << ua/d << ";\tu7%-3=" << ua%d <<"\t!!!" << endl;//!!! 11 cout << endl; 12 cout << "-7/3=" << b/c << ";\t-7%3=" << b%c << endl; 13 cout << "-7/u3=" << b/uc << ";\t-7%u3=" << b%uc <<"\t!!!" << endl;//!!! 14 cout << endl; 15 cout << "-7/-3=" << b/d << ";\t-7%-3=" << b%d << endl; 16 cout << endl; 17 cout << "3/7=" << c/a << ";\t\t3%7=" << c%a << endl; 18 cout << "u3/u7=" << uc/ua << ";\tu3%u7=" << uc%ua <<"\t!!!" << endl;//!!! 19 cout << endl; 20 cout << "3/-7=" << c/b << ";\t\t3%-7=" << c%b << endl; 21 cout << "u3/-7=" << uc/b << ";\tu3%-7=" << uc%b <<"\t!!!" << endl;//!!! 22 cout << endl; 23 cout << "-3/7=" << d/a << ";\t\t-3%7=" << d%a << endl; 24 cout << "-3/u7=" << d/ua << ";\t-3%u7=" << d%ua <<"\t!!!" << endl;//!!! 25 cout << endl; 26 cout << "-3/-7=" << d/b << ";\t-3%-7=" << d%b << endl; 27 return 0; 28 }
运行结果:
1 7/3=2; 7%3=1 2 u7/u3=2; u7%u3=1 !!! 3 4 7/-3=-2; 7%-3=1 5 u7/-3=0; u7%-3=7 !!! 6 7 -7/3=-2; -7%3=-1 8 -7/u3=1431655763; -7%u3=0 !!! 9 10 -7/-3=2; -7%-3=-1 11 12 3/7=0; 3%7=3 13 u3/u7=0; u3%u7=3 !!! 14 15 3/-7=0; 3%-7=3 16 u3/-7=0; u3%-7=3 !!! 17 18 -3/7=0; -3%7=-3 19 -3/u7=613566756; -3%u7=1 !!! 20 21 -3/-7=0; -3%-7=-3
posted on 2017-02-11 11:10 zhangyz017 阅读(3830) 评论(0) 编辑 收藏 举报