C library function - ceil()
Description
C Library Function double ceil(double x) Returns the smallest integer value greater than or equal to x the given value.
ceil() is a function in the C standard library is a function used to return the smallest integer value greater than or equal to the passed argument (that is, rounding toward positive infinity). This function is often used for rounding up in mathematics and engineering.
Declaration
The following is the declaration of the ceil() function.
#include
double ceil(double x);
float ceilf(float x);
long double ceill(long double x);
Parameters
x: A floating-point value.
Return Value
- Returns the smallest integer value greater than or equal to
xthe smallest integer value (rounded up).
Example
The following example demonstrates the use of the ceil() function.
Example
#include
#include
int
main
(
)
{
float
val1
,
val2
,
val3
,
val4
;
val1
=
1.6
;
val2
=
1.2
;
val3
=
2.8
;
val4
=
2.3
;
printf
(
"value1 = %.1lf\n"
,
ceil
(
val1
)
)
;
printf
(
"value2 = %.1lf\n"
,
ceil
(
val2
)
)
;
printf
(
"value3 = %.1lf\n"
,
ceil
(
val3
)
)
;
printf
(
"value4 = %.1lf\n"
,
ceil
(
val4
)
)
;
return
(
0
)
;
}
Let's compile and run the above program, which will produce the following result:
value1 = 2.0
value2 = 2.0
value3 = 3.0
value4 = 3.0
Handling rounding up for multiple values
The following example shows how to handle rounding-up calculations for multiple values:
Example
#include
#include
int
main
(
)
{
double
values
[
]
=
{
4.2
,
5.7
,
3.3
,
0.0
}
;
int
num_values
=
sizeof
(
values
)
/
sizeof
(
values
[
0
]
)
;
for
(
int
i
=
0
;
i
<
num_values
;
i
++
)
{
double
x
=
values
[
i
]
;
double
result
=
ceil
(
x
)
;
printf
(
"ceil(%f) = %f\n"
,
x
,
result
)
;
}
return
0
;
}
Let's compile and run the above program, which will produce the following result:
ceil(4.200000) = 5.000000
ceil(5.700000) = 6.000000
ceil(-3.300000) = -3.000000
ceil(0.000000) = 0.000000
Code Analysis
- Define an array containing multiple floating-point numbers
values. - Use
for, and loop through each value, calling theceil(x)function to perform the rounding-up calculation. - Print the rounding-up result for each value.
Use Cases
ceil() The function has a wide range of uses in many applications, including but not limited to:
- Rounding floating-point numbers, ensuring the result is greater than or equal to the original value.
- Computing upper-bound values in physics and engineering.
- Performing rounding-up operations in financial calculations.
Summary
ceil() The function returns the smallest integer value greater than or equal to the passed argument (rounded up) and is an important tool for handling mathematical calculations and floating-point rounding. Through appropriate use of ceil(), you can achieve accurate handling of numerical values in scientific computing, engineering applications, and financial calculations.
C Standard Library -