How to fix this code in Java?

Asked

Viewed 80 times

0

Good evening, a teacher sent to class some exercises in Java to do, but as we are at the beginning of the course and I had no basis before, I’m having trouble solving it. Someone could guide me?

The code is this:

public class MathUtils {
    public static double average(int a, int b) {
        return a + b / 2;
    }

    public static void main(String[] args) {
        System.out.println(average(2,1));
    }
}

He asks to fix it in a way that works.

1 answer

2


The error is mathematical. a + b / 2 is dividing b by 2 and only then adding a.

Simply add parentheses to the sum a + b:

public static double average(int a, int b) {
    return (a + b) / 2;
}
  • It worked, but I didn’t understand this program structure. Could you explain it to me line by line? In this case I would consider deleting everything and doing so: public class Mathutils { public Static void main(String[] args) { int a, b; avarege = (a+b)/2; System.out.println(avarege); } };}

  • Yes, it is totally correct to write like this. However, with the function average(), you don’t have to worry, for example, about creating variables (ex: a, b) every time that you want to average two values. If the goal of this program is only to average between 2 and 1, I would say that your idea is simpler and more direct. However, when you are creating a larger program, and need to calculate various averages, in various parts of the code, it is good to have functions like these, which can be used several times without having to be rewritten every time.

  • Thank you very much ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.