- Write a program in C to round of floating point number in one line or single statement.
- How to round of a floating point number to the nearest integer.
For Example:
- Round of 15.2 = 15
- Round of 15.8 = 16
- round of 15.0 = 15
Algorithm to round of floating point numbers
Let N be a floating point number.
- If N is a positive number, then add 0.5 to N.(T = N + 0.5)
- If N is a negative number, then subtract 0.5 from N.(T = N – 0.5)
- Now Type Cast T to integer data type(int).
Round of 15.2 = (int)(15.2 + 0.5) = (int)15.7 = 15
Round of 15.8 = (int)(15.8 + 0.5) = (int)16.3 = 16
C program to round of floating point number in one line

# include<stdio.h>
int main() {
float n;
int round;
printf("Enter a floating point number\n");
scanf("%f", &n);
round = (int)(n < 0 ? n - 0.5 : n + 0.5);
printf("Rounded integer : %d", round);
return 0;
}
Output
Enter a floating point number 1.3 Rounded integer : 1 Enter a floating point number 1.8 Rounded integer : 2
C program to round of floating point number using function

# include<stdio.h>
int getRoundOf(float N) {
return (int)(N < 0 ? N - 0.5 : N + 0.5);
}
int main() {
float n;
printf("Enter a floating point number\n");
scanf("%f", &n);
printf("Rounded integer : %d", getRoundOf(n));
return 0;
}
Output
Enter a floating point number -1.3 Rounded integer : -1 Enter a floating point number 2.1 Rounded integer : 2