Not sure how to deal with repeating decimals in C

Viewed 287
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.

3 Answers
#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

use double or float number. in definition and in printf

#include <stdio.h>

int main(void)
{
    double number = (double)2/3;
    printf("%.f", number);
}

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.

Related