I have a problem when making a program, I ask the user to give me two values, the first a price and the second an income, I want to get the change but it doesn't make it exact.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Indica el precio: ");
double pre = sc.nextDouble();
System.out.print("Indica la cantidad que has ingresado: ");
double ing = sc.nextDouble();
double devolver;
devolver = ing - pre;
System.out.print("Su cambio: ");
while (devolver != 0) {
if (devolver >= 2) {
System.out.println("Monedas de 2 euros: " + devolver);
devolver= devolver-2;
}
if (devolver >= 1) {
System.out.println("Monedas de 1 euro: " + devolver);
devolver= devolver-1;
}
if (devolver >= 0.5) {
System.out.println("Monedas de 50 centimos: " + devolver);
devolver= devolver-0.5;
}
if (devolver >= 0.2) {
System.out.println("Monedas de 20 centimos " + devolver);
devolver= devolver-0.2;
if (devolver >= 0.1) {
System.out.println("Monedas de 10 centimos: " + devolver);
devolver= devolver-0.1;
}
if (devolver >= 0.05) {
System.out.println("Monedas de 5 centimos: " + devolver);
devolver= devolver-0.05;
}
In the system.print output it gives me:
Indica el precio: 0,65
Indica la cantidad que has ingresado: 1
Su cambio: Monedas de 20 centimos 0.35
Monedas de 10 centimos: 0.14999999999999997
I don't understand the output of said code or if I have missed something.
This problem is due to the fact that computers work in binary and when working with variables of type float or double they make precision errors when working with values that they cannot represent. if we want to represent 1/3, the result is 0.3333333333333… and so on to infinity. We cannot give an exact value to that operation. And exactly the same thing happens to computers, if they want to represent, for example, 1/100, the result would be 1100110011001100110011001100110011… and so on ad infinitum.
You could next use BigDecimal but you can also change your code to this:
I hope it helps.