How do you convert floating point numbers to integers in C language?
In C language, you can convert a floating-point number to an integer using either type casting or round-down function.
- Use typecasting:
float num = 3.14;
int integerNum = (int)num;
printf("The integer value is: %d\n", integerNum);
- Utilize the rounding function:
#include <math.h>
float num = 3.14;
int integerNum = round(num); //四舍五入
printf("The integer value is: %d\n", integerNum);
Caution: using type coercion will directly truncate the decimal part of a floating-point number, which may result in loss of accuracy; on the other hand, using rounding functions will round the number according to conventions, providing a more precise conversion from floating-point to integer.