GLBasic forum

Main forum => GLBasic - en => Topic started by: spicypixel on 2011-Dec-27

Title: Am I going insane?
Post by: spicypixel on 2011-Dec-27
I want to present a percentage of stars collected from stars totalled as a rating out of 5. This code works perfectly with 5 stars showing when you collect all stars but 0 when you collect anything else. The maths is fine is must be some integer float weirdness. I really can't see what I'm doing wrong lol. Any help is greatly appreciated :)

Code (glbasic) Select

LOCAL starscaught
starscaught = (GE_StarsCollected%/GE_StarsTotal%)*5

FOR starx = 0 TO starscaught-1
DRAWANIM GE_Stars%, 1, (starx*32) + 160 , 234
NEXT


Am I going insane? :)
Title: Re: Am I going insane?
Post by: spicypixel on 2011-Dec-27
OK I sorted it by setting my globals for GE_StarsCollected and GE_StarsTotal to floats and not integer but I would have thought if I'm demanding that the result stored in starscaught to be a float then it should be able to calculate correctly. More fool me????
Title: Re: Am I going insane?
Post by: Wampus on 2011-Dec-27
Its confusing but what happened is normal...I think. If a calculation includes integers but is assigned to a float, as in starscaught# = (GE_StarsCollected%/GE_StarsTotal%)*5, the result will be an integer. From the Data Types page of the GLBasic User Manual (http://www.glbasic.com/xmlhelp.php?lang=en&id=255&action=view):-

Be aware that values typed directly into your code that are written as integers (whole numbers) may force calculations to be done as integer calculations. This may lead to unexpected results when you assign the result of a calculation to a variable that supports a decimal place but get an integer result back.

For example
MyNumber% = 1234       // Integer
Result# = MyNumber / 1000       // Result is a float value

As "Result" has been defined as a floating point number (that is, one that supports decimal places - indicated by the "#"), you would expect that "Result" would contain the value "1.234". Instead, the compiler determines that the "1000" is an integer value (as it doesn't contain a decimal point) and does an integer based calculation. The result of 1234 / 1000 as an integer calculation is "1".