198k views
3 votes
Consider the following code snippet. What is the potential problem with the if statement? double average; average = (g1 + g2 + g3 + g4) / 4.0; if (average == 90.0) { System.out.println("You earned an A in the class!"); }

User HarryH
by
4.3k points

1 Answer

4 votes

Answer:

The if statement use the equality operator == as condition checker. This is not a good option in this context as the average value is a floating point value which could hardly get the perfect rounded value 90.0 to pass the if condition. This will cause the if block would never be executed and incur logical error. The better option is to use >= operator to ensure all the average above or equal to 90.0 will pass the if condition and display the message.

User Bryan C
by
4.8k points