20111128

C語言做四捨五入

四捨五入如果知其道理,其實並沒有很難做。
把握一個原則:浮點數轉成整數,小數部位會全部捨去。
所以最簡單的作法就是,把浮點數加0.5,再轉成整數即可。
因為四以下要捨,五以上要入,所以加0.5。如果是負數,
則減去0.5。若是做四捨五入到小數第一位的話,就先乘10,
再加0.5,再除以10(唯要注意型態轉換),以此類推。

其實math.h中就有round()函式,但是是C99的東西。
或是用floor()跟ceil()實做也是ok的。

以下是程式碼。(寫個大概而已)

#include <stdio.h>

int round(double);

int main(void)
{
    double x;

    scanf("%lf", &x);
    printf("%d\n", round(x));

    return 0;
}

/* round: do round to x */
int round(double x)
{
    if (x > 0)
        return (int)(x + 0.5);

    return (int)(x - 0.5);
}




參考連結:
http://dejob.blogspot.com/2009/01/c-rounding.html
http://blog.xuite.net/freeleo168/Learn/19008875

沒有留言: