What’s the best way to round up item quantities in C++?

0
5
Asked By MellowBirch42 On

I'm new to C++ and building a small catering calculator. The program asks for the number of wedding brunch guests, then calculates how many whole containers or items are needed—for example, egg cartons containing 12 eggs, cantaloupes sold in groups of 8, bread loaves in groups of 24, and juice containers holding 16 gallons.

When I used integers, division truncated the fractional part and sometimes produced too few items. I would rather round up so the result never falls short. I currently store the calculations as double values and apply std::ceil when printing the results. For example, 520 guests produces 44 egg cartons, 65 cantaloupes, 22 loaves of bread, and 33 gallons of juice.

Is using ceil with doubles a reasonable approach here, or would integer arithmetic be better practice?

3 Answers

Answered By CrispRiver7 On

Using std::ceil is perfectly valid for this situation, especially since you’re dividing quantities and need to round upward. There’s no major issue with the approach as written, although you could avoid floating-point values entirely because all of the inputs and outputs represent whole quantities.

Answered By QuietLantern5 On

Another clear integer-based option is to calculate both the quotient and remainder. If the remainder is greater than zero, increment the quotient:

`int quantity = guests / packageSize;`
`if (guests % packageSize != 0) ++quantity;`

This makes the reason for rounding up especially easy to understand while you’re learning.

Answered By SunnyKite18 On

For positive integers, a common way to round integer division upward is `(guests + divisor - 1) / divisor`. So for cartons of 12, you could write `int eggs = (guests + 11) / 12;`. This avoids doubles and floating-point rounding concerns.

MellowBirch42 -

The 11 comes from the divisor minus one: `12 - 1`. For any positive divisor, use `divisor - 1`, so the general form is `(amount + divisor - 1) / divisor`.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.