views:

281

answers:

5

Is there any difference between these:

float foo1 = (int)(bar / 3.0);
float foo2 = floor(bar / 3.0);

As I understand both cases have the same result. Is there any difference in the compiled code?

Note: updated fabs() to floor() as that was the real question

+3  A: 

EDIT: Because the question may have been modified due to confusion between fabs() and floor().

Given the original question example lines:

1.  float foo = (int)(bar / 3.0);

2.  float foo = fabs(bar / 3.0);

The difference is that if bar is negative the result will be negative with the first but positive with the second. The first will be truncated to an integer and the second will return the full decimal value including fractional part.

Amardeep
+7  A: 

Why do you think they will have the same result?

float foo = (int)(bar / 3.0) will create an integer then assign it to a float

float foo = fabs(bar / 3.0 ) will do the absolute value of a float division

bar = 1.0

foo1 = 0; foo2 = 0.33333...

Anders K.
+3  A: 

Yes. fabs returns the absolute value of its argument, and the cast to int causes truncation of the division (down to the nearest int), so the results will almost always be different.

warrenm
A: 

(int) x is a request to keep the integer part of x (there is no rounding here)

fabs(x) = |x| so that it's >= 0;

Ex: (int) -3.5 returns -3; fabs(-3.5) returns 3.5;

In general, fabs (x) >= x for all x;

x >= (int) x if x >= 0

x < (int) x if x < 0

hungh3
Your last statement is wrong; consider your -3 example.
Dennis Zickefoose
x = -3fabs(-3) = 3 (int) -3 = -3; I think the last inequalities hold. Can you elaborate more on why it's wrong?
hungh3
Sorry, I meant -3.5, the example you gave. -3 > -3.5
Dennis Zickefoose
yup, edited. Thanks.
hungh3
+11  A: 

Were you by chance confusing fabs with floor ?

Casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative.

James Curran
I think you hit the nail on the head here. Another difference, if `floor()` is the intent, is if the value of `bar` is too big to fit in an `int`.
Fred Larson