2
int number = round(2/3);
printf("%i", number);

the output is

0

I expected to get 1 as 0.6 recurring should round up - i know for sure that the problem is with recurring decimals as they are always rounded down - I'm not sure how to round up in this kind of scenario.

Klaus D.
  • 13,874
  • 5
  • 41
  • 48
Dev
  • 31
  • 4

3 Answers3

3
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void) {
  double number = round(2.0/3.0);
printf("%0.f", number);
}

Output = 1

You can use double or float for rounding numbers

slckKadeR
  • 59
  • 4
1

use double or float number. in definition and in printf

#include <stdio.h>

int main(void)
{
    double number = (double)2/3;
    printf("%.f", number);
}
Abilogos
  • 4,777
  • 2
  • 19
  • 39
MED LDN
  • 684
  • 1
  • 5
  • 10
1

Without floating point calculations, the following will round to nearest using just integer division:

int a = 2;
int number = (a + 1) / 3;    // = 1

In general, rounding a / b to the nearest integer is equivalent to truncating (a + b / 2) / b.

dxiv
  • 16,984
  • 2
  • 27
  • 49