Use Functions (e.g., round, floor, ceil) to Round Values
In this step, you'll learn how to use rounding functions in C to manipulate floating-point numbers. We'll modify the previous rounding.c
file to demonstrate different rounding techniques.
Open the existing file:
cd ~/project
nano rounding.c
Replace the previous content with the following code:
#include <stdio.h>
#include <math.h>
int main() {
// Declare floating-point variables
float num1 = 3.7;
double num2 = 4.2;
// Round values using different functions
printf("Original values:\n");
printf("num1: %.1f, num2: %.1f\n\n", num1, num2);
// Using round() function
printf("Round function:\n");
printf("round(num1): %.0f\n", round(num1));
printf("round(num2): %.0f\n\n", round(num2));
// Using floor() function
printf("Floor function:\n");
printf("floor(num1): %.0f\n", floor(num1));
printf("floor(num2): %.0f\n\n", floor(num2));
// Using ceil() function
printf("Ceil function:\n");
printf("ceil(num1): %.0f\n", ceil(num1));
printf("ceil(num2): %.0f\n", ceil(num2));
return 0;
}
Compile the program with the math library:
gcc rounding.c -o rounding -lm
./rounding
Example output:
Original values:
num1: 3.7, num2: 4.2
Round function:
round(num1): 4
round(num2): 4
Floor function:
floor(num1): 3
floor(num2): 4
Ceil function:
ceil(num1): 4
ceil(num2): 5
Key points about rounding functions:
round()
: Rounds to the nearest integer
floor()
: Rounds down to the nearest integer
ceil()
: Rounds up to the nearest integer
-lm
flag is used to link the math library when compiling
%.0f
format specifier displays integers without decimal places