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.
Videos
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.
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
I'm trying to write a function that (kind of) emulates the ceiling function in the math library, in a way that is more useful for my purposes. The code I've written is not working as expected. It should take two integer arguments, divide one by the other, and round up to the nearest integer no matter what the result is.
Ex: 2/2=1 --> answer is 1; 10/3=3.333... --> round up to 4.
This is my code:
int ceiling(int number, int value){
float a = number/value;
int b = number/value;
float c = a - b;
if(c!=0){
b=b+1;
}
return b;
}Using the examples above,
ceiling(2,2); would return 1, as expected.
ceiling(10,3); returns 3, when it should return 4.
My thought process is that if a is a float, then 10/3 should be 3.33333..., and if b is an int, then 10/3 should be 3. If c is a float, a-b should be 0.33333..., then since c!=0, ceiling should increment b and return that value. Where am I going wrong?
Been trying to figure this out but keep running to dead ends.