C/C++求余运算符

本文详细介绍了C++中求余运算符(%)的基本用法及注意事项,并通过实例演示了不同类型变量组合下求余运算的结果表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

转载于:https://www.cnblogs.com/zhangyz/p/6388850.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值