Long vs. Float?
4 messages in this thread
I have a question, and I would appreciate someone taking the time to
reply.
Here it is:
Given the following code, is there something 'bad' about it?
….
float a_attack = 0.0;
float a_rv = 0.0;
long a1 = 50;
long attack_factor = 5000;
long sold = 0;
long a_soldiers = 250;
a_attack = (a1 * 100) / attack_factor;
a_rv = (100 – a_attack) / 100;
sold = (long) a_soldiers * a_rv;
….
What I am curious about is whether it is 'bad' to do a multiplication with
a long and a float? It is my understanding that division and
multiplication return a floating point number. What I want the program to
do is to drop the stuff to the right of the decimal, so I have made the
target variable a long. Will this work all of the time?
I am trying to chase down a lockup bug with a door program I wrote many
moons ago.
I would appreciate your help.
-mark=
Otto Pilot Engaged..
Unless your denominators ever become zero (divide by zero gurus), there's
nothing "wrong" with that. There's a sequence of promotion when evaluating
expressions. In simplest terms, if you mix floats and ints or longs, the
result is the float.
Hi Mark,
The only problem I can see is that an integer divided by an integer will
yield an integer. On pg 37 in the old "The C Programming Language", by
Kernighan and Ritchie. Thus the line: a_attack = (a1*100)/attack_factor;
will alway have an integral value stored in a real. Also an integer
multiplied by an integer in an integer.
The real problem is that if you have
float = (int1*int2)/int3;
you may have precision problems. If (int1*int2) is greater than will
fit into an int, you'll have a problem, for example. A bigger problem
is that (int1*int2) is itself an int, so (int1*int2)/int3 is done as
INTEGER division, not floating point division. This can give you
funny values like (10*20)/201 = 0, for example: you probably wanted
your float to be set to some floating point value near 1, but it got
truncated due to the integer division.
The easiest way to make sure you keep the precision correct is to cast
one or more of the operands to each subexpression to float. i.e.,
float f;
int i1, i2, i3;
…
f = ((float)i1*i2)/i3;
Since i1 is cast to float, the multiplication is done in float; since
the result of the multiplication is float, the division is also done
in float. So that one cast did the whole trick for you.
Note that in your particular example, this won't change the answer,
since the float gets 1.0 in either integer or floating point math.
–Doug