codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
#include <stdio.h> // rounds n (upwards) to a multiple of f while preserving the sign-bit of n // The above comment is confusing. Is "upwards" towards 0? If so, the comment // needs to be changed. // HOWEVER, I don't think this is what the function is supposed to do! // static inline int round_multiple_nosign(int n, int f) { int nn, ns; nn = (n >= 0) ? n : -n; ns = (n >= 0) ? 1 : -1; if (nn % f == 0) return n; // n == nn * ns else return ns * (n + f - (n % f)); // This should be ns * (nn + f - (nn % f)); } // My version // afz: away from zero static inline int round_multiple_afz(int n, unsigned f) { int sign = n < 0 ? -1 : 1; n *= sign; return sign * (n + f - n % f); } int main(void) { printf("%d\n", round_multiple_nosign(-30, 16)); printf("%d\n", round_multiple_afz(-30, 16)); return 0; }
Private
[
?
]
Run code
Submit