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

0
1
Asked By MellowBirch42 On

I'm new to C++ and am building a small catering calculator. The user enters the number of guests, and the program calculates how many whole containers or items are needed—for example, egg cartons that hold 12 eggs, fruit portions in groups of 8, bread loaves serving 24, and juice containers serving 16. Since buying too little would be a problem, each result needs to be rounded up rather than truncated down. I currently divide using double values and print the result with std::ceil, but I'm wondering whether that's good practice or whether there's a cleaner integer-based approach. For example, with 520 guests, the program should produce 44 egg cartons, 65 fruit portions, 22 loaves, and 33 gallons of juice.

3 Answers

Answered By CopperLark7 On

std::ceil works correctly here, so your current approach is valid. However, because the input and divisors represent whole numbers, you can avoid floating-point arithmetic and use integer division instead. A common formula for rounding positive integer division upward is (amount + divisor - 1) / divisor. For example, (guests + 12 - 1) / 12 calculates the number of egg cartons needed.

MellowBirch42 -

That makes sense. I was wondering why the extra 11 was added, and now I understand that it’s the divisor minus one.

Answered By NorthVale3 On

You can also calculate the quotient and remainder directly: divide the guest count by the container size, then increase the quotient by one if the remainder is nonzero. In code, that means using / for the quotient and % for the remainder. The compact (guests + divisor - 1) / divisor version does the same thing for positive values and only performs one division.

Answered By QuietOrbit88 On

An int does not really round down; integer division simply discards the remainder because an integer cannot store a fractional part. A double can represent fractions and std::ceil can round them upward, but floating-point values are approximations. For this particular problem, integer arithmetic is clearer and avoids unnecessary floating-point calculations. You could store guests as an int and calculate each quantity with the upward-division formula.

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.