Reputation: 119
Within my Activity
I am attempting to divide
two values then multiply
them by 100 in order to give a percentage score.
My issue is that the percentage score is always zero, even though this is impossible with the values I am using.
What am I doing wrong?
Declaring the 2 variables at start of activity:
int score = 0;
int totalQuestions=0;
Onclick logic showing how they are calculated:
public void onClick(View v) {
if (checkForMatch((Button) v)) {
//increment no of questions answered (for % score)
totalQuestions++;
//increment score by 1
score++;
} else {
//increment no of questions answered (for % score)
totalQuestions++;
}
}
public void writeToDatabase() {
// create instance of databasehelper class
DatabaseHelper db = new DatabaseHelper(this);
int divide = (score/ totalQuestions );
int percentageScore = (divide * 100);
Log.d("Pertrace", "per score "+ percentageScore);
Log.d("divide", "divide "+ divide);
// Adding the new Session to the database
db.addScore(new Session(sessionID, "Stroop", SignInActivity
.getUserName(), averageMedLevel, medMax, averageAttLevel,
attMax, percentageScore, myDate, "false", fileNameRaw, fileNameEEGPower, fileNameMeditation, fileNameAttention));
// single score, used for passing to next activity
single = db.getScore(sessionID);
}
Note: from my Trace logs i can see that is it the int divide
that is zero, why would this be the case considering that score
and totalQuestions
are always greater than zero? E.g. 20 and 25.
Upvotes: 1
Views: 134
Reputation: 172378
The reason is this line
int divide = (score/ totalQuestions);
You are dividing the numbers and storing in an int.
You need to store in a double
double divide = (double)score / totalQuestions;
If you want the result as int
double divide = (double)score / totalQuestions;
int percentageScore = (int) Math.ceil(divide * 100);
Upvotes: 2
Reputation: 201399
You are performing integer division. First cast score to a double (so you get floating point math), then I would use Math.round()
to round the result of the multiplication. For example,
int score = 3;
int totalQuestions = 4;
double divide = ((double) score / totalQuestions);
int percentageScore = (int) Math.round(divide * 100);
System.out.println(percentageScore);
Output is the expected
75
Upvotes: 1
Reputation: 9011
You are saving them in int
. Save values in float
or double
.
Also, when division occurs, the intermediate result is saved in one of the variable that is used in division. If that is an int, it will be truncated
before being saved in double
. So do something like double divide = (double)score * totalQuestions
Upvotes: 2
Reputation: 66866
The operands need to be float
or double
, and so does the variable you put it in:
double divide = (double) score/ totalQuestions;
Upvotes: 0