C++ 取模运算

      取模运算要求两个操作数都是整数或者能隐式地转换成整数类型。如果两个操作数不是整数,且不能隐式地转换成整数,将发生编译错误,例如:

	cout<< 5.4 % 3 <<endl; // error: invalid operands of types 'double' and 'int' to binary 'operator%'

      取模运算结果的正负是由左操作数的正负决定的。C99标准规定:如果%左操作数是正数,那么取模运算的结果是非负数;如果%左操作数是负数,那么取模运算的结果是负数或0。

#include <iostream>
using namespace std;


int main() {
    
    

	int a = 5;
	int b = 2;
	int c = -3;
	int d = -13;
	
	cout<<"a % b = "<<a%b<<endl;

	cout<<"a % c = "<<a%c<<endl;


	cout<<"d % c = "<<d%c<<endl;

	cout<<"d % a = "<<d%a<<endl;
}

输出如下:

a % b = 1
a % c = 2
d % c = -1
d % a = -3

猜你喜欢

转载自blog.csdn.net/weixin_40315481/article/details/107992977