0
  • I think ceil() function should have given 2.000000 instead of 1.000000 when I write :
int main() {

    printf( "%f", ceil(5/3) );

    return 0;
}

and floor() function gives 1.000000 as expected. I don't understand why ceil is giving 1.000000.

  • The snippet below prints 0 and I don't know why :
int main() {
    printf("%d", ceil(5.0/3));

    return 0;
}
lbonn
  • 2,499
  • 22
  • 32
  • 2
    The second snippet has undefined behaviour, since `ceil()` returns `double`. The `%d` format tells `printf()` to ASSUME the corresponding argument is an `int` and, if anything other than `int` (i.e. `double` in this case) gives undefined behaviour. – Peter Jan 04 '20 at 07:42
  • 1
    `5/3` is `1` as that is integer division. – chux - Reinstate Monica Jan 04 '20 at 10:48

1 Answers1

3

The signature of ceil is double ceil(double x);.

printf( "%f", ceil((double)5/3) ); should work as you are expecting. 5/3 is integer division. The ceil function receives 1 as a result of the integer division (as the digits after the decimal are discarded) and can do very little from there.

Casting atleast one of the operands of the / operator to double will result in a floating point division and the digits after the decimal will be preserved.

You need to pass a fractional number to ceil for it to do what you want.

In the comments below, Chux provides an alternative method of doing this.

babon
  • 3,615
  • 2
  • 20
  • 20
  • 1
    Coercing a floating point division can be done with more gently with `1.0*` as in `1.0*a/b` than a cast. A good compiler with emit efficient code either way. Casts such a `(float)` can lose information as code may later change `a,b` from `int` to `double` and then the cast in an unedited `(float)a/b` is not only not needed, it tosses away precision and range and can result in a wrong quotient. – chux - Reinstate Monica Jan 04 '20 at 10:55