-2
/**
  * practice
  */
 public class practice {
 
    public static void main(String[] args) {
        int sc,sst,maths,eng,sans,agg_marks;
        double perc;
        sc = 60;
        sst = 49;
        maths = 79;
        eng = 99;
        sans = 96;
        agg_marks = sc+sst+maths+eng+sans;
        perc = agg_marks*100/500;
        System.out.println(agg_marks);
        System.out.println(perc);

i expected it to have no problem with calculation of percentage and it would be accurate but it shows 76 instead of 76.6.

meriton
  • 68,356
  • 14
  • 108
  • 175
  • When posting code, please use the "{}" button in the editor toolbar to mark it as code, so stackoverflow doesn't mangle the formatting. (I did it for you in this case, but please do it yourself in the future) – meriton Jul 02 '23 at 17:01
  • And you could simplify `n*100/500` to `n/5` – Valerij Dobler Jul 02 '23 at 19:33

2 Answers2

1

The operators * and / use the data type of their arguments to perform the calculation. Since agg_marks, 100 and 500 are integers, it uses integer multiplication and division, which rounds down to the nearest integer.

If you wish to use double division, make sure that at least one argument is a double, for instance by declaring agg_marks as double, or writing 100.0 (which is a double) rather than 100 (which is an integer), or 500.0 rather than 500.

(it's sufficient for one argument to be a double, because arguments of mixed types use the larger type)

meriton
  • 68,356
  • 14
  • 108
  • 175
0

Calculate the percentage below, you should be good

perc = agg_marks*100/500.0; // only if numerator/denominator is float division doesn't capture the floating part