934 views

What is the correct way to round off $x$, $a$ $\text{float}$ to an $\text{int}$ value?

1. $y=(\text{int})(x+0.5)$
2. $y=\text{int} (x+0.5)$
3. $y=(\text{int}) x+0.5$
4. $y=(\text{int})(\text{int})x+0.5)$

I think both A and C is the correct option.

Logic for this is: Suppose x is 2.75,

for y = (int)(x+0.5)

= (int)(3.25)

which implies y to be 3,

whereas for y = (int)x+0.5

= (int)2.75+ 0.5

which implies y to be 2 because 0.5 when added to an integer implicitly 0.5 will become 0.

Rounding off x has been implemented correctly in both of the options. So both of them has to be correct.

Kindly suggest anyone if otherwise.

I think C is the correct answer because in the question it is clearly mentioned to round off the value of x and not the the result as a whole. If the question said the round of the value of y (the result of x+0.5) then A would have been the correct answer. Please correct if wrong.

which implies y to be 2 because 0.5 when added to an integer implicitly 0.5 will become 0.

Incorrect. When 0.5 is added to an integer, the integer is promoted to a float. The float is not levelled down to an int. I suggest you to read about implicit typecasting in C.

Option A is correct, and Option C is not.

Here the correct way to round of the float values are :

whenever, a decimal value of x <5 the ans would be the floor value of x .

and when  decimal value of x >5 the ans would be the ceil value of x.

for eg.

if x=5.75 , the correct round off value will be 6. i.e y=6.:

so here (int)(5.75+0.5) = (int) (6.25) = 6.

and if x=5.25 ,the correct round off value will be 5. i.e y=5.:

so here (int)(5.25+0.5) = (int) (5.75) = 5

so adding 0.5 in x and returning floor value  will return the correct round off value . which is equivalent to OPTION "A" i.e (int )(x+0.5)   Here Type casting int means give the floor value of x+0.5 which is what we want in the answer

hence Option "A" is correct.

### 1 comment

Just rounding off the value of x is stated in the question, so why do we have to worry about the result as a whole?

I think option B is correct.

Let us suppose x = 2.75

Now y= int ( x +0.5) = int (2.75+0.5)= int (3.25)= 3
In the question.

Given ::   x = float

Say p = int

To round off “float” variable  to “int” variable in C.

p = (int)x

Hence according to question option C) seems to be more suitable.

1
1,486 views