-
Four types of rounding in C.
-
zero-ward rounding (math.)
-
trunc function (C99)
- Use of trunc
-
trunc function (C99)
-
Floor finishing
- Use of the floor function
-
Round up
- Use of the ceil function
-
discard four, but treat five as whole (of decimal points)
-
round function (C99)
- Use of the round function
-
round function (C99)
- Demonstration of four rounding methods
-
zero-ward rounding (math.)
Four types of rounding in C.
zero-ward rounding (math.)
As shown.
It can be found that the C language a and b are not rounded to the nearest whole number, but directly discard the fractional part. (a rounds to -3, b rounds to 3.) This is called thezero-ward rounding (math.). Also.Default rounding in c
It can be seen from the figure that both -2.9 and 2.9 are rounded in the direction of 0.
trunc function (C99)
C language<>
There is also a zero-integer function in the library, which has a floating-point return value and can be forced to int if needed.
Use of trunc
Note that %d does not accept floating-point types directly. Floating-point types have a different layout in memory space than integers, so be aware of this.
If you want to use it as an integer, you need parentheses.(int)
Forced type conversion.
Floor finishing
The name is a bit strange, it is a translation of the function floor.
Also known as rounding down, rounding to the left, and rounding to negative infinity.
Use of the floor function
Round up
Also known as rounding to the right, rounding to positive infinity, from the ceil function.
Use of the ceil function
discard four, but treat five as whole (of decimal points)
round function (C99)
Use of the round function
Demonstration of four rounding methods
#include<>
#include<>
int main()
{
const char * format = "%.1f \t%.1f \t%.1f \t%.1f \t%.1f\n";
printf("value\tround\tfloor\tceil\ttrunc\n");
printf("-----\t-----\t-----\t----\t-----\n");
printf(format, 2.3, round(2.3), floor(2.3), ceil(2.3), trunc(2.3));
printf(format, 3.8, round(3.8), floor(3.8), ceil(3.8), trunc(3.8));
printf(format, 5.5, round(5.5), floor(5.5), ceil(5.5), trunc(5.5));
printf(format, -2.3, round(-2.3), floor(-2.3), ceil(-2.3), trunc(-2.3));
printf(format, -3.8, round(-3.8), floor(-3.8), ceil(-3.8), trunc(-3.8));
printf(format, -5.5, round(-5.5), floor(-5.5), ceil(-5.5), trunc(-5.5));
return 0;
}