fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. div_t
  4. divide (int numer, int denom)
  5. {
  6. div_t result;
  7. result.quot = numer / denom;
  8. result.rem = numer % denom;
  9. /* The ANSI standard says that |QUOT| <= |NUMER / DENOM|, where
  10. NUMER / DENOM is to be computed in infinite precision. In
  11. other words, we should always truncate the quotient towards
  12. zero, never -infinity. Machine division and remainer may
  13. work either way when one or both of NUMER or DENOM is
  14. negative. If only one is negative and QUOT has been
  15. truncated towards -infinity, REM will have the same sign as
  16. DENOM and the opposite sign of NUMER; if both are negative
  17. and QUOT has been truncated towards -infinity, REM will be
  18. positive (will have the opposite sign of NUMER). These are
  19. considered `wrong'. If both are NUM and DENOM are positive,
  20. RESULT will always be positive. This all boils down to: if
  21. NUMER >= 0, but REM < 0, we got the wrong answer. In that
  22. case, to get the right answer, add 1 to QUOT and subtract
  23. DENOM from REM. */
  24. if (numer >= 0 && result.rem < 0)
  25. {
  26. ++result.quot;
  27. result.rem -= denom;
  28. }
  29. return result;
  30. }
  31.  
  32. int main()
  33. {
  34. int num = -42, div = 5;
  35. std::div_t res = divide(num, div);
  36. std::cout << "Result: " << res.quot << ":" << res.rem << std::endl;
  37.  
  38. }
  39.  
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
Result: -8:-2