四捨五入
最近、二種類の四捨五入する関数を見た。
これと
static long round(float x) { long ans = (long)x; if (x - (float)ans >= 0.5) return ++ans; else if (x - (float)ans <= -0.5) return --ans; return ans; }
これ。
static long round(float x) { return (x > 0.0f) ? (long)(x + 0.5f) : -(long)(-x + 0.5f); }
得られる結果は同じのはずだけど、
前者はなんだか技巧的?というか無駄に複雑で後者は一行に圧縮。
いろんな書き方があるもんだ。