Having Issues Printing Floats

bombar

Member
So I'm trying to figure out some averages in a display script to print them out to the user and I have the following block:
Code:
	float avgSchematics = numSchematics/numTimesTaken;
	print("Number of Times Taken: '" + numTimesTaken + "' totalSch: '" + numSchematics + "' avg:'" + avgSchematics + "'");

And it produces this output:
Code:
Number of Times Taken: '8' totalSch: '17' avg:'2.0'

When it should be 2.125, so I would at least expect to see 2.1

What am I doing wrong?
 

Bale

Minion
What are doing wrong is dividing an integer by an integer. Sorry. This is not intuitively obvious, but when you divide an integer by an integer, java's result is an integer. It will only produce a float when either the numerator or denominator is a float.

What you need to do to fix this is to change one of those ints into a float before dividing. Like this:


Code:
	float avgSchematics = to_float(numSchematics)/numTimesTaken;
	print("Number of Times Taken: '" + numTimesTaken + "' totalSch: '" + numSchematics + "' avg:'" + avgSchematics + "'");
 
Last edited:
Top