centurion937
centurion937

Reputation: 43

C: How do I make a number always round up

I'm wanting to make a function that calculates a cost based on time. For any time less than three hours, it would return a flat rate charge of $2. For each hour or part of an hour over that, it would charge an additional $0.50. Hours are input by user as a float data type to 2 decimal places. How can I make it to where it will always round up the time to a whole hour? Here's the code I have so far for the function:

int calculateCharges(float hours)
{
 if (hours <= 3){
    return 2.00
}
else

Upvotes: 1

Views: 79680

Answers (2)

Kevin Avignon
Kevin Avignon

Reputation: 2903

To answer your query, you should study your variable type. You use hours as a in, but you return a 2.00 which is a floating number( aka not a integer)

#include <math.h>

double calculateCharge(double hours)
{ 
 //To use accurately the ceil function from Math, the parameter should be a double!
  double calculateTime = ( hours <3) ? 2 : (2+ceil(hours-3)*0.50); 
  return calculateTime;
}

Include the math.h header to be able to use the Math struc. It is a really help structure when you have to compute values, you can calculate the sinus of a number for instance. In our situation, the ceil function will always return the value to round up to the nearest integer. You can learn more about it here : http://www.techonthenet.com/c_language/standard_library_functions/math_h/ceil.php Oh and also, you said less than three hours, but in your function you say less or equals to 3. Make sure you actually use the good operator or you could end up with results you are not expecting while running your function!

Oh, you can look up the ternary operator there in order to have a better understanding of it since it's a bit obscure the first time :http://msdn.microsoft.com/en-us/library/ty67wk28.aspx

Hope it helps you :)

Upvotes: 0

Freyja
Freyja

Reputation: 40944

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

Upvotes: 4

Related Questions