-1

It seems that I have to put the total and the mark given as a double for this to work. I am just wondering if anyone has an explanation as to why I cannot store the score and total as a an int (as these are going to be whole numbers) yet keep percentage as a double.

enter image description here

THess
  • 1,003
  • 1
  • 13
  • 21
Liam Wild
  • 1
  • 2
  • Can you show us some codes? – Cyrille Con Morales Jun 25 '20 at 09:37
  • 4
    Welcome to Stack Overflow. Unfortunately you haven't shown any code, so we can really only *guess* at what's wrong. The guess is that you've made the common mistake of performing integer division and then converting the result to a double - where integer division of 80/100 would give an answer of 0, for example. You'd want to perform the division itself in floating point. Or multiply by 100 to start with, and keep the percentage as an integer, potentially. – Jon Skeet Jun 25 '20 at 09:37
  • image now attached. Sorry, new to the posting. – Liam Wild Jun 25 '20 at 09:42
  • Please add your code as text instead of an image. That way we can help you easier and more quickly. Thank you. – THess Jun 25 '20 at 09:43
  • Does this answer your question? [Int division: Why is the result of 1/3 == 0?](https://stackoverflow.com/questions/4685450/int-division-why-is-the-result-of-1-3-0) – Progman Jun 25 '20 at 09:44
  • Thanks progman, that has helped. I was fine with using a double I just wanted to know why using the two int's would not work. many thanks. – Liam Wild Jun 25 '20 at 09:46

1 Answers1

0

Integer division in Java will return the exact number of times one number is divisible by another. 80 is not divisible by 100, even once, so 80/100 = 0 in terms of integer division. You need a double or float to get a decimal result.

To fix it, ensure all the relevant types are double, e.g.:

float score;
float total;

Alternatively, you can cast the calculation, but this is not good practice:

float result = (float) score/total * 100;
Shan S
  • 658
  • 5
  • 18