C: How do I make a number always round up

First of all, you use the data type int, which cannot hold fractional values (and will implicitly round them towards zero, even before the function is ever called.) You should use double instead, since this is the proper datatype for fractional numbers.

You would also want to use the ceil(x) function, which gives the nearest whole number larger than or equal to x.

#include <math.h>

double calculateCharges(double hours)
{
  if (hours <= 3) {
    return 2.00;
  } else {
    // return $2.00 for the first 3 hours,
    //  plus an additional $0.50 per hour begun after that
    return 2.00 + ceil(hours - 3) * 0.50;
  }
}

Leave a Comment