Page 1 of 1

Problem with division

PostPosted: Thu Jan 31, 2008 2:46 am
by zygoth
I have a health bar with 56 animations and I want it to reflect the health of the player. Here's my code:

Draw Actor -->healthbar
animpos = abs(((health / maxhealth) * 55) - 55)

the absolute value is there because the health bar is going the opposite direction it needs to.
I tried writing (health / maxhealth) as a float variable and replacing it with the float variable "floaty" but it still didn't work

like this

Draw Actor -->healthbar

float floaty
floaty = health / maxhealth
can anybody help me? It seems like this code should work.

Re: Problem with division

PostPosted: Thu Jan 31, 2008 3:03 am
by stevenp
see post blelow

Re: Problem with division

PostPosted: Thu Jan 31, 2008 6:26 am
by Fuzzy
floaty is a terrible name for a variable. Its too close to float.

I can see that you would get a division by zero error with that, possibly. Is that the problem?

Multiplication can take the place of division thus avoiding a division by zero error. if you wanted to divide by 4, for instance, you can multiply by 0.25.

Re: Problem with division

PostPosted: Thu Jan 31, 2008 8:52 am
by DilloDude
If health is an integer, then it will do an integer division, so the result is cast to an integer. If you use (double)health, health will be cast to a real number first, fixing the problem:
Code: Select all
animpos = abs((((double)health / maxhealth) * 55) - 55);

Re: Problem with division

PostPosted: Thu Jan 31, 2008 10:22 pm
by pyrometal
I think the problem is that you are trying to assing a real value to animpos (which is an integer). To fix this, try add either floor() or ceil() to your function to truncate your vale to the nearest integer.

Code: Select all
animpos = floor(abs(((health / maxhealth) * 55) - 55));


I think you should also consider what dillodude has mention as well, although I do beleive it is possible without the pointer specifier.

That's all!

-- Pyro

Re: Problem with division

PostPosted: Thu Jan 31, 2008 11:00 pm
by zygoth
Thanks a lot, guys, it worked... I was getting really frustrated with it, but i put in your code and it worked fine.

Re: Problem with division

PostPosted: Fri Feb 01, 2008 1:08 am
by pyrometal
I'm curious, did flooring your value help? I had that problem in the past as well and that's how I fixed it.