Home »
C programs »
C preprocessors programs
Define a Macro to round a float value to nearest integer in C
C macro to round a float value to the integer: Here, we are implementing a program to convert a given float value to the nearest integer with the help of a Macro.
By IncludeHelp Last updated : March 10, 2024
Given a float value and we have to round the value to the nearest integer with the help of Macro in C language.
Macro Definition
#define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
Example
Input:
float val1=10.00f;
float val2=10.23f;
float val3=10.50f;
float val4=10.65f;
Output:
After round val1=10
After round val2=10
After round val3=11
After round val4=11
C program to define a Macro to round a float value to nearest integer
#include <stdio.h>
//Macro
#define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
//Main code
int main(void)
{
float val1=10.00f;
float val2=10.23f;
float val3=10.50f;
float val4=10.65f;
printf("After round val1=%d\n",round(val1));
printf("After round val2=%d\n",round(val2));
printf("After round val3=%d\n",round(val3));
printf("After round val4=%d\n",round(val4));
return 0;
}
Output
After round val1=10
After round val2=10
After round val3=11
After round val4=11
C Preprocessors Programs »