#include // has abs() // Find sign (plus or minus) of integer. (Used by divide_and_round().) // Pre: None. // Post: Return value is 1 if x >= 0, -1 otherwise. int sign(int x) { if (x >= 0) return 1; else return -1; } // Divide integers with rounding. // Pre: "divisor" is not zero. // Post: Return value is "dividend" divided by "divisor", // rounded to the nearest integer. int divide_and_round(int dividend, int divisor) { // To avoid any confusion about what "%" means for negative // numbers, we will work with absolute values and then // restore the proper sign at the end. // Compute quotient, remainder of abs(dividend) / abs(divisor). int Q = abs(dividend) / abs(divisor); int R = abs(dividend) % abs(divisor); // Compute absolute value of result: Add one to quotient if // remainder is at least half of divisor. int abs_result; if ((2 * R) >= divisor) abs_result = Q + 1; else abs_result = Q; // Return result with proper sign. if (sign(dividend) == sign(divisor)) return abs_result; else return -abs_result; }