Akashhuyaar's blog

By Akashhuyaar, 3 years ago, In English

I was having trouble while using ceil function in c++, I would like to explain the mistake I was making by example


ceil(5/2)=2 ceil(5/2.0)=3

the mistake here is that I am dividing 5 by 2 in int type so it returns 2 and ceil function won't do anything as 2 is already an integer number, whereas in float type division 5/2.0 will give 2.5 which will be converted into 3 by ceil function.

And there's an another issue with inbuilt ceil function that it loses precision after some point so you can use (x+y-1/y) instead, as the ceil function. Like this,

long long ceil(float x, float y){
     return (x+y-1)/y;
}

or you can simply use ceil(x/(double)y),suggested by PyPcDev or

 inline long long ceil_div(long long a, long long b) { 
    return a / b + ((a ^ b) > 0 && a % b); 
} 

suggested by dutinmeow

It's really a small thing but it took me some time to figure out so I thought I should share it :)

Full text and comments »

  • Vote: I like it
  • +17
  • Vote: I do not like it