*sigh* ...problem calculating percentage.

BlitzMax Forums/BlitzMax Beginners Area/*sigh* ...problem calculating percentage.

Sokurah(Posted 2010) [#1]
Sometimes I think I'm thick or something, but something that always causes me to grind to a halt is when I have to convert something to a percentage.

I hope someone can save me some time before I spend too much time on it. :)

So, assuming I have 2 vars.

EnemiesKilled%
ShotsFired%

How do I calculate the hitrate of my shots as a percentage?

(yeah, I know...basic algera, but like I said...I must be a bit thickheaded) :o)


Oddball(Posted 2010) [#2]
(EnemiesKilled/ShotsFired)*100
You may need to convert them to floats first though.
(Float(EnemiesKilled)/Float(ShotsFired))*100



Sokurah(Posted 2010) [#3]
Ahh, perfect. Thanks Oddball.

Silly how a simple thing like that give one problems. :)


Czar Flavius(Posted 2010) [#4]
Alternatively, without floats

(EnemiesKilled*100)/ShotsFired



Zethrax(Posted 2010) [#5]
If a single value in an equation is a float, then the entire equation will be evaluated as a float equation, so using a float value for the 100 (100.0 instead) would get the job done.

(EnemiesKilled/ShotsFired)*100.0


Floyd(Posted 2010) [#6]
That's not the way it works.

The integer expression (EnemiesKilled/ShotsFired) would be evaluated first. The result would be converted to a float and multiplied by 100.0.

For example (1/2)*100.0 is 0.0 rather than the 50.0 you might expect.


Kryzon(Posted 2010) [#7]
Therefore, use:

(EnemiesKilled*100.0) / ShotsFired


Gabriel(Posted 2010) [#8]
That's not the way it works.

I think Bill was probably thinking of a single value in an expression, rather than the whole equation.

To borrow your example, all three of these:

(1.0/2)*100.0 

(1/2.0)*100.0 

(1.0/2.0)*100.0 


should give you the correct value.


H&K(Posted 2010) [#9]
If you remember from school,

B Brackets first
O Orders (ie Powers and Square Roots, etc.)
DM Division and Multiplication (left-to-right)
AS Addition and Subtraction (left-to-right)

Now the computer will religiously follow this for each operator, and will only increase accuracy when you say, so

(Int/Int) * Float ____________ (1/2)*100.0
(INt)* Float = Float = 0 So even tho the answer is a float, the answer is wrong, because we loose accuracy in the division

Int*Int/FLoat ____________ (1*100)/2.0
Int/Float ____________ 100/2.0
Float ____________ 50.0

So as Czar nearly had

(EnemiesKilled*100)/Float (ShotsFired)

IS an int multiplication and a float division, which looses no accuracy but is possibly faster than two float operations

(In the Old Old days it would definitely be faster, I dont really know how efficient cpu/compilers are now adays)