in Programming in C recategorized by
1,792 views
3 votes
3 votes

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)$
in Programming in C recategorized by
by
1.8k views

3 Comments

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.
1
1

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.

0
0


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.

0
0

3 Answers

4 votes
4 votes

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?

0
0
0 votes
0 votes
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
0 votes
0 votes
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.
Answer:

Related questions