Convert a Floating-point Value to an Integer in C
On this page (6sections)
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);
}
Related Pages
- C Archive — Browse all C Archive.
- 2+3 and 5 are not equal In C — More in c blog.
- Confusing Array in C ( Array Representation and Initialization ) — More in c blog.
- The Use of * and & in C/C++ — More in c blog.
Frequently Asked Questions
What does this C program do?
It is a C example program that demonstrates Convert a Floating-point Value to an Integer, including the complete source code and the expected sample output.
How do I compile and run this C program?
Save the code in a `.c` file, compile it with `gcc filename.c -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses core C syntax, illustrating a common pattern in C programming.