Implement ceil function in C

I have two questions regarding the ceil() function.

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

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

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

  • How can I implement my own ceil function in C. Please provide some basic recommendations.

Thanks.

+4
source share
4 answers

The ceil() function is implemented in the libm.so math library. By default, the linker does not contact this library when called through the gcc interface. To link this library, pass -lm to the gcc command line:

 gcc main.c -lm 
+3
source

Try the following:

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

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

+5
source

The prototype function of ceil is:

 double ceil(double) 

I assume that the type of the variable count not of type double. To use ceil in C, you must 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 several types:

 #include <cmath> // ... double count = 3.0; double result = std::ceil(count/2.0); 
+3
source
 double ceil (double x) { if (x > LONG_MAX) return x; // big floats are all ints return ((long)(x+(0.99999999999999997))); } 
-1
source

Source: https://habr.com/ru/post/1309231/


All Articles