C Programming - Floating Point Issues - Discussion
Discussion Forum : Floating Point Issues - General Questions (Q.No. 6)
6.
We want to round off x, a float, to an int value, The correct way to do is
Answer: Option
Explanation:
Rounding off a value means replacing it by a nearest value that is approximately equal or smaller or greater to the given number.
y = (int)(x + 0.5); here x is any float value. To roundoff, we have to typecast the value of x by using (int)
Example:
#include <stdio.h>
int main ()
{
float x = 3.6;
int y = (int)(x + 0.5);
printf ("Result = %d\n", y );
return 0;
}
Output:
Result = 4.
Discussion:
24 comments Page 3 of 3.
Well wisher said:
1 decade ago
Why we should add 0.5 to x :(x+.5)
We can get the answer directly.
y=(int)(x);
I hope this is enough.
In case the round off vale shold not be a min one then we can go for (x+0.5)
Because if u type the above code having x=3.99
Then the roound off value would be 3.
That is not we are looking for.
We can get the answer directly.
y=(int)(x);
I hope this is enough.
In case the round off vale shold not be a min one then we can go for (x+0.5)
Because if u type the above code having x=3.99
Then the roound off value would be 3.
That is not we are looking for.
Vishak said:
1 decade ago
@Ashish: i too thought the same why cant we ? is there a proper explanation ?
Nikhil said:
1 decade ago
Why answer is (int)(x) +0. 5?
Ashish Gupta said:
1 decade ago
We can use both
a) y= int(x+0.5)
b) y= (int)(x+0.5)
a) y= int(x+0.5)
b) y= (int)(x+0.5)
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers