-2

I need to create simple C programming which look like this

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

This is my example

#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;
}

The answer for i become 1.0 but i am expecting 1.5 and j is 2.0 but my expectation is 1.5 I need a few line to make it happen right?

zappy
  • 1,864
  • 3
  • 18
  • 36
Rushdiey
  • 133
  • 1
  • 1
  • 15

1 Answers1

2

[for C]

This would do for values greater or equal 0:

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

For values less or equal 0 it should be:

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

This would do for any:

double to_be_rounded = ...;
double rounded = round(2. * to_be_rounded) / 2.;
alk
  • 69,737
  • 10
  • 105
  • 255