...

View Full Version : Rounding Problem



ah288
09-24-2007, 01:13 AM
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.



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
}

thanks

Dunna
10-04-2007, 04:45 AM
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.



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 = su;m / ( 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
}

thanks

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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum