• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 779
  • Last Modified:

What do u think? My own floor/ceil func...

hi guys
  I am out of points so pls. do try to help... :(
I am writing my own floor/ceil implementation without using those from 'math.h' lib and I want your opinions on the efficiency and possible bugs/flaws on my coding design...
I am using macros..
/* conversion from float/double to nearest integer */
#define floor(a) (((a - (int)a)>0)? (int)a:a)
#define ceil(a) (((a - (int)a)>0)? ((int)a + 1):a)

usage :
  1. if I key in a = 22.3, (a-(int)a) = 22.3 - 22=0.3 > 0
so I would ret (int)a = 22 ( for Floor() )
  2. if I key in a = 22.3, (a-(int)a) = 22.3 - 22.0 = 0.3
>0 so I would ret ((int)a+1) = 22+1 = 23 (for Ceil())

I am not sure whether the syntax is ok as I haven't tested it yet... :)

1 Solution
It's is very dangerous to use such an function as a macro. e.g. Try

double x=23.2;

printf ("%d", floor (x++));

What will be the result and the value after this statement. Better you use a real function.
To make your floor function more efficient you could eliminate the test ((a - (int)a)>0) and just define floor as

#define floor(a) (int)a

The test that you currently have just filters out numbers that are integers. Therefore numbers that are already integers are not converted.  This test does not have to be performed because if the number is already an integer, typecasting it as an integer won't change it anyway!  Defining it as above will save the time of a subtraction and a test.

My advice applies only to your floor function.  As far as I can see, the ceiling function requires the test.

HahoAuthor Commented:
Thank rbr and scrapdog ( thanks for the obvious!!I missed that...  :)),
I am waiting to see if anybody else has any comments/answers....
cause it is important that this 'floor'/'ceil'  works without any major flaws or bugs as I am using it for a commercial application...
BTW, I heard that floor/ceil from the math.h lib has some possible flaws...
I don't know how true it is ... do u guys know anything bout this??

What if you have

 double x = INT_MAX + 1.5;

What possible flaws have you heard of in math.h
Who wrote your math.h?

#define floor(a) (int)a
doesn't work for negative a
HahoAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get 10% Off Your First Squarespace Website

Ready to showcase your work, publish content or promote your business online? With Squarespace’s award-winning templates and 24/7 customer service, getting started is simple. Head to Squarespace.com and use offer code ‘EXPERTS’ to get 10% off your first purchase.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now