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;
int a = 5; int b = 2; int result = (a + b - 1) / b; result is 3, not 2
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; }
The result of 5 / 2 rounded up is 3
Round Up Using Ceil() Function.
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; }
The result of 5 / 2 rounded up is 3
No comments:
Post a Comment