Enjoy an ad free experience by logging in. Not a member yet? Register.


Results 1 to 2 of 2
Thread: Rounding Problem

09242007, 01:13 AM #1
 Join Date
 Sep 2007
 Posts
 1
 Thanks
 0
 Thanked 0 Times in 0 Posts
Rounding Problem
Heres my problem:
I created a method that returns a handicap in integer form. Before you can return it, however, you must cast it as an int. My problem arises in some cases where the handicap returned is 1 too high. I'm wondering where my logic may be wrong in some cases; so far.. I can't find the problem.
Code:public int seeHandicap () { int highScore; float average = 0, sum = 0; double handicap; highScore = hiScore(); // returns highest score in array for ( int i = 0; i < SCORES; i++ ) sum = sum + scores[i]; // adds all scores in array together sum = highScore; // highest score is thrown out average = sum / ( SCORES  1 ); // float = float/int (default float,right?) handicap = ( average  PAR ) * HANDICAP_P; // (equation for finding handicap) if ( handicap < 0 ) return 0; return (int)handicap; // casts double handicap as an integer }
Last edited by ah288; 09242007 at 01:16 AM.
10042007, 04:45 AM
#2
 Join Date
 May 2004
 Location
 New Hampshire, America
 Posts
 246
 Thanks
 0
 Thanked 2 Times in 2 Posts
depending on your compiler, this might be the problem
Change: "average = sum / ( SCORES  1 );"
To: "average = (float)(sum / (float)(SCORES  1));"
because the int causes the division by a float to result in an int, which is the most exact unit that it could result in.
Your least precise unit of measurement or division cannot be less precise then the result.
Last edited by Dunna; 10042007 at 04:49 AM.