1

I'm having trouble rounding up to the next integer, because of integer truncation. Basically, I want x/n (both integers) to be 9 but I keep getting 8. How do I divide two integers and get an integer that is the rounded up version of the actual decimal number? Simply using ceil(25.0/3.0) won't work for me, because in my actual program, x and n are integer values input by the user.

Also, why isn't the 3rd line I tried below able to run? Whenever I try to typecast inside the ceil function, I get a message saying "undefined reference to ceil."

int x = 25;
int n = 3;
int numOfStrings = ceil(((double)x) / n);
Angie
  • 41
  • 1
  • 4
  • Your 3 lines work for me, though I had to import - https://onlinegdb.com/ptKa5M4e2 – xdhmoore Oct 29 '22 at 05:38
  • https://stackoverflow.com/a/2745086/378779 – kmoser Oct 29 '22 at 05:41
  • 2
    If the numbers are always positive you can use `numOfStrings = (x + n - 1) / n;`, which is likely faster than converting to/from floating point. – Brendan Oct 29 '22 at 07:01
  • @Brendan It also works for negative numbers (rounding towards positive infinity). To reduce problems with arithmetic overflow it can be changed to `numOfStrings = x / n + !!(x % n)` but that generates slightly more code. – Ian Abbott Oct 29 '22 at 08:22
  • @IanAbbott: C89 allowed the remainder of division to be a different sign to the dividend (but C99 changed it to "must have same sign"); which means (for C89, in theory) you can end up with `5/(-2) + !!( 5%(-2)) == (-2) + !!(-1) == (-2) + 1 == -1` (unless I got something wrong)? – Brendan Oct 29 '22 at 11:02
  • @Brendan OK neither method works for all combinations of positive and negative. In all C versions `n / d * d + n % d == n` has always been true. C99 always rounds the result of division towards 0 (by discarding any fractional part). C89 rounds down if `n` and `d` are both positive, otherwise it is implementation defined whether it rounds up or down. – Ian Abbott Oct 29 '22 at 21:31

1 Answers1

3

Floating point is always a problem.

It's simpler to just add the 0 ('false') or 1 ('true') of whether or not there is any remainder (modulo).

#include <stdio.h>

int main() {
    int n = 3;

    for( int x = 21; x < 30; x++ )
        printf( "n:%d x:%d  x/n:%d\n", n, x, x/n + !!(x%n) );

    return 0;
}
n:3 x:21  x/n:7
n:3 x:22  x/n:8
n:3 x:23  x/n:8
n:3 x:24  x/n:8
n:3 x:25  x/n:9  // <=====
n:3 x:26  x/n:9
n:3 x:27  x/n:9
n:3 x:28  x/n:10
n:3 x:29  x/n:10

AND, you should be checking/preventing the possibility of division by zero (left as an exercise.)

Fe2O3
  • 6,077
  • 2
  • 4
  • 20