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

问题描述 投票:-3回答:1

这个问题在这里已有答案:

我需要创建看起来像这样的简单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我需要一些线来让它发生吗?

javascript c
1个回答
2
投票

[对于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.;
© www.soinside.com 2019 - 2024. All rights reserved.