C++ modulo operation

      Modulus operation requires that both operands are integers or can be implicitly converted to integer types. If the two operands are not integers and cannot be implicitly converted to integers, a compilation error will occur, for example:

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

      The sign of the result of the modulo operation is determined by the sign of the left operand. The C99 standard stipulates: if the left operand of% is positive, then the result of the modulo operation is non-negative; if the left operand of% is negative, the result of the modulo operation is negative or 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;
}

The output is as follows:

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

Guess you like

Origin blog.csdn.net/weixin_40315481/article/details/107992977