A simple ceil doubt


#include <iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
	// your code goes here

    int ans=0;
    ans = ceil((11-2)/2) + ceil((2-1)/2);
    cout<<ans;
	return 0;
}


I am not getting that it’s showing ans as 4 instead it should as 6.
but this works for this case ans = ceil((6-7)/2) + ceil((7-13)/2) this gives the answer as expected -3;

1 Like

It’s because you are using integers and not double values so the resulting division is integer division.

From the code it does ceil (9/2) - ceil (1/2) = ceil (4) - ceil (0) which is 4.
Since the decimal values are truncated. For correct result you can do ceil((11-2)/2.0) + ceil((2-1)/2.0).

1 Like

This should answer your question.

#include <bits/stdc++.h>
using namespace std;

int main() {
	// your code goes here

    int ans = 0;
    ans = ceil((11.0 - 2) / 2) + ceil((2.0 - 1) / 2);
    cout << ans;
	return 0;
}

but this works for this case ans = ceil((6-7)/2) + ceil((7-13)/2) this gives the answer as expected -3;

Without using the double… As I compiled and got correct ans

but this works for this case ans = ceil((6-7)/2) + ceil((7-13)/2) this gives the answer as expected -3;

Without using the double… As I compiled and got correct ans.

That’s because the Integer division also gives -3.
(-1/2) + (-6/2) = 0 + -3 which will be -3 as well, nothing to do with ceil function.

Thanks buddy

Yes, as said by @justgoogleit , for some expressions, the result is same irrespective of whether the numbers are ints or floats.