c 语言实现 round 方法研究

C语言默认没有提供round方法,这里简单研究下round方法的实现

int x;x = floor(1.2); // x is set to 1
x = floor(1.8); // x is set to 1
x = (int)1.8; // x is set to 1 (Explicit Narrowing Conversion)
x = 1.8; // x is set to 1 (Implicit Narrowing Conversion)
x = ceil(1.2); // x is set to 2
x = ceil(1.8); // x is set to 2

round方法作用是把某个浮点数变成最接近她的整数,如下
x = round(1.2); // x is set to 1
x = round(1.8); // x is set to 2

下面看看 +0.5 后的结果
x = (int)(1.2 + 0.5); // x is set to 1
x = (int)(1.8 + 0.5); // x is set to 2

下面看看负数时 -0.5 后的结果
x = (int)(-1.2 – 0.5); // x is set to -1
x = (int)(-1.8 – 0.5); // x is set to -2

根据上面的结果,可以得出一个简单的round方法实现
int round(double number){ return (number >= 0) ? (int)(number + 0.5) : (int)(number – 0.5);}
很简单吧。根据系统的环境、编译器,把int类型改为 long类型,有些编译器中int和long的长度是一样的,但是有些不一样。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>