简单C编程向上/向下舍入到最接近的0.5

时间:2017-12-26 09:56:41

标签: javascript c

我需要创建看起来像这样的简单C编程

1.1 and 1.2 to 1.0
1.3 and 1.4 to 1.5
1.6 and 1.7 to 1.5
1.8 and 1.9 to 2.0

这是我的例子

#include <stdio.h>
#include <math.h>
 int main()
{
       float i=1.3, j=1.7;
       printf("round of  %f is  %f\n", i, round(i));
       printf("round of  %f is  %f\n", j, round(j));
       return 0;
}

i的答案变为1.0,但我期待1.5j 2.0,但我的期望是1.5 我需要几行才能让它成为现实吗?

1 个答案:

答案 0 :(得分:2)

[for C]

这适用于大于或等于0的值:

double to_be_rounded = ...;
double rounded = trunc(2. * to_be_rounded + .5) / 2.;

对于小于或等于0的值,它应该是:

double to_be_rounded = ...;
double rounded = trunc(2. * to_be_rounded - .5) / 2.;

这适用于任何:

double to_be_rounded = ...;
double rounded = round(2. * to_be_rounded) / 2.;