Round Up the Result of Integer Division in C++.

In C++, the integer division of two integers produces a result that is truncated toward zero. For example, if we divide 5 by 2, the result would be 2 instead of 2.5, because the decimal part is truncated. However, there are times when we want the result of integer division to be rounded up to the nearest integer. 


Round Up Integer Division using Formula.

Suppose we want to compute the result of integer division a/b and round it up to the nearest integer. We can do this using the following formula:


int result = (a + b - 1) / b;

The idea behind this formula is that we add b-1 to the numerator, which ensures that the division result is always rounded up. 
Example:
int a = 5;
int b = 2;
int result = (a + b - 1) / b;
result is 3, not 2

In this example, the numerator (a+b-1) is 6, and the denominator (b) is 2. The result of the division is therefore 3, which is the closest integer to 2.5, the exact result of the division.
Note: This formula works only for positive integers. If a or b can be negative, you should use a different formula. (alert-passed)

C++ program that demonstrates how to round up the result of integer division:

//C++ code to round up integer division
#include <iostream>
using namespace std;

int main() {
    int a = 5;
    int b = 2;
    int result = (a + b - 1) / b;
    cout << "The result of " << a << " / " << b << " rounded up is " << result << endl;
    return 0;
}
Output:
The result of 5 / 2 rounded up is 3

Round Up Using Ceil() Function.

C++, you can use the ceil() function from the <cmath> header to round up a floating-point value to the nearest integer. However, it's important to note that ceil() works with floating-point values, not with the result of integer division.
Note: If you want to round up the result of integer division, you would need to convert the integers to floating-point values before using ceil() (alert-success)

C++ Code Implementation:

//C++ code to round up integer uisng ceil fun
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int a = 5;
    int b = 2;
    double result = ceil(static_cast<double>(a) / b);
    cout << "The result of " << a << " / " << b << " rounded up is " << result << endl;
    return 0;
}
Output:
The result of 5 / 2 rounded up is 3

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS