1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
#include <iostream>
int ABS(int);
int DIV(int, int);
int REM(int, int);
void display(int, int, int, int);
int main()
{
int a = -25; // dividend
int d = -3; // divisor
int quotient = 0;
int remainder = 0;
if(a > 0 and d > 0)
{
quotient = DIV(a,d);
remainder = REM(a,d);
}
else if(a < 0 and d > 0)
{
quotient = -DIV(ABS(a),d) - 1;
remainder = -REM(ABS(a),d) + d;
}
else if(a > 0 and d < 0)
{
quotient = -DIV(a, ABS(d));
remainder = REM(a,ABS(d));
}
else
{
quotient = DIV(ABS(a),ABS(d)) + 1;
remainder = -REM(ABS(a),ABS(d)) - d;
}
display(a,d, quotient, remainder);
return 0;
}
// absolute value
int ABS(int n)
{
if (n < 0)
return 0 - n;
else
return n;
}
// integer division
int DIV(int aa, int dd)
{
int result{0};
while(aa - dd >= 0)
{
aa -= dd;
result++;
}
return result;
}
// remainder
int REM(int aa, int dd)
{
return aa - DIV(aa,dd) * dd;
}
void display(int aa, int dd, int qq, int rr)
{
std::cout
<< " dividend a: " << aa << '\n'
<< " divisor d: " << dd << "\n\n"
<< " quotient q: " << qq << '\n'
<< "remainder r: " << rr << '\n';
if( aa == dd * qq + rr)
{
std::cout << aa << " = (" << dd << " x " << qq << ") + " << rr << '\n';
}
else
std::cout << "Error\n";
}
|