Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

10
  • 9
    @bitc: For negative numbers, I believe C99 specifies round-to-zero, so x/y is the ceiling of the division. C90 didn't specify how to round, and I don't think the current C++ standard does either. Commented Apr 30, 2010 at 14:46
  • 6
    See Eric Lippert's post: stackoverflow.com/questions/921180/c-round-up/926806#926806 Commented Apr 30, 2010 at 14:53
  • 3
    Note: This might overflow. q = ((long long)x + y - 1) / y will not. My code is slower though, so if you know that your numbers will not overflow, you should use Sparky's version. Commented Apr 30, 2010 at 15:09
  • 17
    The second one has a problem where x is 0. ceil(0/y) = 0 but it returns 1. Commented May 27, 2013 at 0:52
  • 3
    @OmryYadan would x == 0 ? 0 : 1 + ((x - 1) / y) resolve this safely and efficiently? Commented Apr 5, 2017 at 0:50