Thursday 1 March 2012

The floor Function in C & C++

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

double floor (double)
float floorf(float)
long double floorl(long double)

The floor function returns the integer nearest to the argument but not greater than it. The function rounds down except where your argument is an integer in which case it returns the same value.

The ceil and floor functions are odd. What’s odder is the fact it calculates an integer yet returns a float. Why not return an integer? The only reason I can think of relates to math with integers versus floats, but it’s a guess.

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 floor function in <cmath> library.\n\n");
printf("The floor function takes a float value and returns\n");
printf("the nearest integer not greater than the argument passed.\n\n");

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

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

printf("Attempt #2\n");
printf("floor(88.2) returns: %6.2f\n", floor(88.2));
printf("88.0 is nearest to 88.2 and not greater than 88.2.\n\n");

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

printf("Attempt #4\n");
printf("floor(88.8) returns: %6.2f\n", floor(88.8));
printf("89.0 is nearest to 88.8, but is greater so return 88.\n\n");

printf("Attempt #5\n");
printf("floor(88.999999) returns: %6.2f\n", floor(88.999999));
printf("89.0 is nearest to 88.999999, but is greater so return 88.\n\n");

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

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

printf("Attempt #2\n");
printf("floor(-88.4) returns: %6.2f\n", floor(-88.4));
printf("-88.0 is nearest but greater than -88.4 so return -89.\n\n");

printf("Attempt #3\n");
printf("floor(-88.8) returns: %6.2f\n", floor(-88.8));
printf("-89.0 is nearest and not greater than -88.8.\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