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

标签 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.5j2.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/

相关文章:

c++ - 使用适用于 iOS 的 openCV 拼接图像的问题

Javascript 像 jquery 一样显示/隐藏

javascript - 更改西类牙语网站的 HTML

javascript - 我应该使用 <td> 还是 <div> 和嵌套的 <div> 来包含缩略图

C - 两个数组之间的 AND 运算符

c++ - C/C99/C++/C++x/GNU C/GNU C99 中枚举的签名

javascript - MVC5在jquery脚本中更改图像src

javascript - 延迟加载 vs Combine/Minify vs CDN Javascript (AngularJS)

c - 由于 free() 函数导致的运行时错误

c - 浮点异常 C