Modulo Operations in Programming With Negative Results | C ++ program to illustrate modulo operations using the above equation ; Function to calculate and return the remainder of a % n ; Type casting is necessary as ( int ) / ( int ) will give int result , i . e . - 3 / 2 will give - 1 and not - 1.5 ; Return the resultant remainder ; Driver Code ; Modulo of two positive numbers ; Modulo of a negative number by a positive number ; Modulo of a positive number by a negative number ; Modulo of two negative numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; int floorMod ( int a , int n ) { int q = ( int ) floor ( ( double ) a / n ) ; return a - n * q ; } int main ( ) { int a , b ; a = 9 ; b = 4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << floorMod ( a , b ) << " STRNEWLINE " ; a = -9 ; b = 4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << floorMod ( a , b ) << " STRNEWLINE " ; a = 9 ; b = -4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << floorMod ( a , b ) << " STRNEWLINE " ; a = -9 ; b = -4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << floorMod ( a , b ) << " STRNEWLINE " ; return 0 ; }