我需要创建如下所示的简单 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.5
和j
是 2.0
但我的期望是1.5
我需要几行代码才能实现它,对吗?
最佳答案
[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.;
关于javascript - 简单 C 编程向上/向下舍入到最接近的 0.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47976766/