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.

Ishika Dhanraj said:   1 decade ago
Question is Round off.

So if x = 7.2 is rounded than we need 7(rounded value) That's why we add. 5 in it int (7.2+.5) =7.

If x = 7.6 than int (7. 6+. 5) = int (8. 1) = 8.

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.

Sravan said:   2 decades ago
Is any difference between int and (int) ?

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!

Vamshi krishna said:   1 decade ago
I think here is the question to round of x and not the y to which it is assigning so i think (int)x+0.5 is appropriate...!!!

If not can anyone give me a proper explanation???

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

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

Abha said:   1 decade ago
According to me ans should be C because type castng is done to variable and not to a constant term. Tell me whether my perception is wrong or right. ?

Anuj Kumar 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.

Vinoth said:   1 decade ago
Sravan int is different from (int).in given program is compiled in C++ compiler.
In C language we use paranthesis to a variable.
eg:y=int (x)
here x is an float variable and y is an integer variable.
In C++ we put paranthesis to data type.
Eg:y=(int) x
eg we take x=5.6
in question asked is rounding int value(y) for given float value(x) so we add 0.5 to that number.Then the final result is
1.in C language
y=int (x+0.5)
2.in C++
y=(int) (x+0.5)
the result is same in both C and C++ compilers y=6.
ALL THE BEST...


Post your comments here:

Your comments will be displayed after verification.