Location>code7788 >text

Four types of rounding

Popularity:594 ℃/2024-09-19 11:29:54

catalogs
  • Four types of rounding in C.
    • zero-ward rounding (math.)
      • trunc function (C99)
        • Use of trunc
    • 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
    • Demonstration of four rounding methods

Four types of rounding in C.


zero-ward rounding (math.)

As shown.

image-20240502180459967

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

image-20240502203220627

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.

image-20240502182325013


Use of trunc

image-20240502222958451

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.

image-20240502211936753

image-20240502203203237


Use of the floor function

image-20240502223257986


Round up

Also known as rounding to the right, rounding to positive infinity, from the ceil function.

image-20240502221803375

image-20240502221916354


Use of the ceil function

image-20240502223221177


discard four, but treat five as whole (of decimal points)


round function (C99)

image-20240502223527209


Use of the round function

image-20240502223401492


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;
}

image-20240502224455627