I can not divide two numbers correctly

后端 未结 6 506
情深已故
情深已故 2021-01-17 17:44
int percent = (score/numberOfQuestions)*100;
progressText.setText(score+\"/\"+numberOfQuestions+\"  \"+percent+\"%\");

returns 0% no matter what I

相关标签:
6条回答
  • 2021-01-17 17:55

    score/numberOfQuestions will always provide a number between 0 and 1. You have two choices depending upon how accurate you need your computation. For most things, you can change the expression to (score * 100)/numberOfQUestions. This will give you two digits of accuracy. A problem would occur if score * 100 overflowed an int. Given your variable names, I doubt this would happen in this case. The second possibility would be to convert the expression to double for the computation.

    0 讨论(0)
  • 2021-01-17 17:58
    int percent=(int)(((double)score/numberOfQuestions)*100);
    
    0 讨论(0)
  • 2021-01-17 18:16

    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.

    0 讨论(0)
  • 2021-01-17 18:17

    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..

    0 讨论(0)
  • 2021-01-17 18:17

    You're using an int (integer) to store that percentage. Try using float or double instead making score and number of questions float or double too (Thanks for teh comments, I totally skipped this...). If you have issues showing the value, I suggest you use DecimalFormat to format it.

    Rather than using pure int math to calculate and store the percentage, I suggest this other alternatives if you want to have decimals in your result.

    0 讨论(0)
  • 2021-01-17 18:21

    Check your integer math. Your code won't work without casting for small values, so just move the operations around:

    int percent = 100*score/numberOfQuestions;
    
    0 讨论(0)
提交回复
热议问题