0
Bug In Java Introduction Course
In the module "Control Flow" is anm excercise to code regarding a bill and tip amount. I entered the code here which is OK: import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double billAmount = sc.nextDouble(); double tipAmount = billAmount/100*15; System.out.println(tipAmount); } } But one of the four tests (Test 3) fail. It shows me that my output is 232.20000000000002 and the expected output is 232.2. I tried in mobile app (OS) and WIndows Desktop and receive this error on both environments.
2 Answers
+ 5
Attila Kipfer ,
billAmount/100*15
billAmount*15/100
should mathematically give the same result. but in reality these operations can give *different results* due to floating-point precision issues and integer division behavior.
> see also:
https://softwareengineering.stackexchange.com/questions/101163/what-causes-floating-point-rounding-errors?utm_source=perplexity
+ 3
Try this.
double tipAmount = billAmount * 15 / 100;
I'm not sure why, but divided by 100 always works better than by 15.