Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can not divide two numbers correctly

Tags:

java

android

int percent = (score/numberOfQuestions)*100;
progressText.setText(score+"/"+numberOfQuestions+"  "+percent+"%");

returns 0% no matter what I tired. I tried casting it to int, double, float

Why does it return 0% for a number like score=5 numberOfQuestions=8?

like image 959
code511788465541441 Avatar asked Oct 10 '12 18:10

code511788465541441


2 Answers

The problem is that divide two integers gives you the integer part of the result. So, (score/numberOfQuestions) will be always 0.
What you should do is

int percent = (score * 100 / numberOfQuestions);

Then the *100 will be executed first, then the divide will give you correct result.

like image 125
LeeNeverGup Avatar answered Sep 20 '22 01:09

LeeNeverGup


You need to cast on either of them: -

float percent = ((float)score/numberOfQuestions)*100;

Since, 5 / 10 is already 0.. Casting the final result to any type will give you 0 only, as in below code: -

float percent = ((float)(score/numberOfQuestions))*100;

This will also give you 0.0. Since you are casting 0 to float. Doesn't matter..

like image 40
Rohit Jain Avatar answered Sep 20 '22 01:09

Rohit Jain