4

I have two questions regarding ceil() function..

  1. The ceil() function is implemented in C. If I use ceil(3/2), it works fine. But when I use ceil(count/2), if value of count is 3, then it gives compile time error.

    /tmp/ccA4Yj7p.o(.text+0x364): In function FrontBackSplit': : undefined reference toceil' collect2: ld returned 1 exit status

    How to use the ceil function in second case? Please suggest.

  2. How can I implement my own ceil function in C. Please give some basic guidelines.

Thanks.

Seki
  • 11,135
  • 7
  • 46
  • 70
AGeek
  • 5,165
  • 16
  • 56
  • 72

4 Answers4

6

Try this out:

#define CEILING_POS(X) ((X-(int)(X)) > 0 ? (int)(X+1) : (int)(X))
#define CEILING_NEG(X) (int)(X)
#define CEILING(X) ( ((X) > 0) ? CEILING_POS(X) : CEILING_NEG(X) )

Check out the link for comments, proof and discussion: http://www.linuxquestions.org/questions/programming-9/ceiling-function-c-programming-637404/

Thanks to Vilhelm Gray and carveone for pointing out that the linked definition of CEILING_NEG(X) is incorrect.

nintendo
  • 69
  • 1
  • 1
  • 3
    This is incorrect for negative values: ceiling always returns the smallest integer **greater than** or equal to the argument given (which for negative numbers means toward zero rather than away). – Vilhelm Gray Apr 05 '13 at 13:43
  • 1
    Test test and test again. ceil(-6.2) is -6. The macros give -7. It's wrong. – carveone Aug 14 '13 at 10:32
3

The ceil() function is implemented in the math library, libm.so. By default, the linker does not link against this library when invoked via the gcc frontend. To link against that library, pass -lm on the command line to gcc:

gcc main.c -lm
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
3

The prototype of the ceil function is:

double ceil(double)

My guess is that the type of your variable count is not of type double. To use ceil in C, you would write:

#include <math.h>
// ...
double count = 3.0;
double result = ceil(count/2.0);

In C++, you can use std::ceil from <cmath>; std::ceil is overloaded to support multiple types:

#include <cmath>
// ...
double count = 3.0;
double result = std::ceil(count/2.0);
Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
-1
double ceil (double x) {
    if (x > LONG_MAX) return x; // big floats are all ints
    return ((long)(x+(0.99999999999999997)));
}