Wednesday 29 February 2012

The ceil Function in C & C++


The <math.h> library in C has several functions to manipulate floats to get integer portions. The ceil function is one:

double ceil(double)
float ceilf(float)
long double ceill(long double)

The ceil function returns the integer nearest to the argument but not less than it. It’s an odd function. The function rounds up except where your argument is an integer in which case it returns the same value. What’s odder is the fact it calculates an integer yet returns a float. Why not return an integer? Not sure, but I suspect there’s some reason. The short answer is I don’t find this function, on its own, very useful.

Here is a snippet from the C standard (C11, N1570).



Sample Code.

I created this sample code in Visual C++ 2010 as a console application.

// The standard library includes the system function.
#include <cstdlib>

// C++ standard I/O library
#include <cstdio>

// The math library.
#include <cmath>

int main()
{

// Header.
printf("Using the ceil function in <cmath> library.\n\n");
printf("The ceil function takes a float value and returns\n");
printf("the nearest integer not less than the argument passed.\n\n");

printf("Positive Numbers\n\n");

printf("Attempt #1\n");
printf("ceil(88.0) returns: %6.2f\n", ceil(88.0));
printf("88.0 is nearest and not less than 88.0.\n\n");

printf("Attempt #2\n");
printf("ceil(88.2) returns: %6.2f\n", ceil(88.2));
printf("88.0 is nearest to 88.2, but is less than it so it returns 89.0.\n\n");

printf("Attempt #3\n");
printf("ceil(88.5) returns: %6.2f\n", ceil(88.5));
printf("88.5 is equidistant between 88.0 & 89.0, but 88.0 is less than 88.5.\n\n");

printf("Attempt #4\n");
printf("ceil(88.8) returns: %6.2f\n", ceil(88.8));
printf("89.0 is nearest to 88.8.\n\n");

printf("Negative Numbers\n\n");

printf("Attempt #1\n");
printf("ceil(-88.0) returns: %6.2f\n", ceil(-88.0));
printf("-88.0 is nearest and not less than -88.0.\n\n");

printf("Attempt #2\n");
printf("ceil(-88.4) returns: %6.2f\n", ceil(-88.4));
printf("-88.0 is nearest and not less than -88.4.\n\n");

printf("Attempt #3\n");
printf("ceil(-88.8) returns: %6.2f\n", ceil(-88.8));
printf("-89.0 is less than -88.8 so it returns -88.0\n\n");

// keep console window open
system("pause");

// return some value
return 0;

} // end main

Here is the console window:


No comments:

Post a Comment