Sign in to follow this  

Getting zero with division of two integers?

This topic is 2081 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am trying to get health bars working correctly based on a ratio of the character's health to his maximum health. At first it works fine when his health is full, the bar is at it's full length. As soon as he has lost some health, the bar goes to zero even though the health value is not at zero. This is what I'm doing, copied directly from my code:

IN MAIN GAME CLASS:
[CODE]spriteBatch.Draw(healthBar, new Rectangle((int)bottomGUIPosition.X + 520, (int)bottomGUIPosition.Y + 25, (int)(character.healthRatio * 200), (int)healthBar.Height), Color.White);

spriteBatch.Draw(healthBarOutline, new Rectangle((int)bottomGUIPosition.X + 520, (int)bottomGUIPosition.Y + 25, 200, (int)healthBar.Height), Color.White);[/CODE]

IN CHARACTER OBJECT CLASS:
[CODE]healthRatio = health / maxHealth;[/CODE]

The variable healthRatio is a float, so I have no idea what the problem is. When the health is 145 and the maxHealth is 150, healthRatio should be set to .966667, but instead it goes to zero.
The value is being updated in the character object every frame.
I realize the code isn't very clean right now as too many things are hard coded in, but its just a prototype I started an hour or so ago, so please excuse the mess. Many thanks to whoever can enlighten me as to the cause of this issue. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

Share this post


Link to post
Share on other sites
Just clarifying what Nik02 said, the data type that the result is being stored in doesn't matter here; what's important is the data types of the variables being operated on. With "health / maxHealth", if both are integers, it will generate an integer result, which just happens to then be stored in a float. But the damage has already been done - because the division was done using integers, you're getting a result of 0.

What you want is something like:[code]healthRatio = (float) health / maxHealth;[/code]

Share this post


Link to post
Share on other sites

This topic is 2081 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this