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
y = (int)(x + 0.5)
y = int(x + 0.5)
y = (int)x + 0.5
y = (int)((int)x + 0.5)
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 2 of 3.

Narendra jain said:   1 decade ago
For rounding of we have to use only int (x) because we have to round of only x and also remember what the syntax of explicit type conversion.

Ravindra said:   1 decade ago
(int)((int) x+0.5) This is also correct. It also rounds off. Then why only a option. D option also correct. Reply.

Aenk said:   1 decade ago
If we enter x=3.3 it means 3<x<3.5 we get 3 value so in this example is .5 addition is not needed.

MrMino said:   10 years ago
The answer should be C:


float x = 4.2;
printf("%f\n", (int)x + 0.5 );

Outputs 4.500000.

Ganga said:   1 decade ago
What is return function can you explain for me?

Why it z return0 we can also put only return know!

Rani said:   1 decade ago
But option (A)=4
option(B)=3
means both are correct we need only round off not say Floor or ceil

Vishak said:   1 decade ago
@Ashish: i too thought the same why cant we ? is there a proper explanation ?

Kanta patidar said:   1 decade ago
option (a)=4
option(c)=3
option(d)=3
it means tino option is right

Ashish Gupta said:   1 decade ago
We can use both

a) y= int(x+0.5)

b) y= (int)(x+0.5)

Anshul Jain said:   10 years ago
Why option C is wrong? Please explain any one.


Post your comments here:

Your comments will be displayed after verification.