Convert a Floating-point value to an Integer in C
Convert float value to an int or Round float value
we can convert very easily,
For Converting floating point value, add 0.5 and convert to integer we can get correct answer,
floating_point_value + 0.5 and Convert to int
Explanation:
here,
you can convert floating point to integer but the straight conversion has some problem.we cannot get the correct value.
if x value 1.9 means.
flaot x=1.9
int a = 1.9
now a has value of 1.it is not the correct answer.then, only we add 0.5 then convert integer.
Example
float x=1.9,y=2.4;
int a,b;
a = (int)(x+0.5);
b = (int)(y+0.5);
now you get correct answers,
a has 2.
also,b has 2.
Example Program for Convert float value to an int:
void main()
{
// Declaring Variables
float x=1.9,y=2.4;
int a,b;
printf("Value Of x:%f",x);
printf("Value Of y:%f",y);
// Simple Conversion
a = (int)(x+0.5);
b = (int)(y+0.5);
printf("Value Of a:%d",a);
printf("Value Of b:%d",b);
}
Read More Articles
- Use of getch(),getche() and getchar() in C
- Switch Case Statement Example Program In C Programming Language
- C Character Set
- Convert a Floating-point value to an Integer in C
- Data Input and Output gets and puts Example Program In C
- Special Operators In C
- Pointer Representation and Pointer Example Programs
- C Data Input and Data Output
- Simple While Loop Example Program In C Programming Language
- Data Output printf and putchar Example Program In C
- C Introduction
- C Operators
- Storage Classes In C
- C Pointers
- File Management
- C Identifiers
- Loop Control Statements
- Hello World - Simple C Program
- C Array
- Single Character Output Function : putchar()
- C Reserve Words
- C Specific Properties and Implementation
- If else Statement Example Program In C Programming Language
- If Statement Example Program In C Programming Language
- Confusing Array in C ( Array Representation and Initialization )