1

I am having trouble getting the correct result from the output. Some input give the right and some don't. For example, when I put 499 I get $29.939999999999998 but when I put 500 I get $25.0.

-Enter the number of copies to print: 499
The total cost is: $29.939999999999998

-Enter the number of copies to print: 500
The total cost is: $25.0

This is my code: What am I doing wrong exactly?

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the number of copies to print: ");
    double numberOfCopies = in.nextDouble();
    double cost;
    double subtotal;
    double totalAmount;

    if(numberOfCopies >= 500) {
        cost = 0.05 / numberOfCopies;
        subtotal = numberOfCopies * cost;
        totalAmount = subtotal * numberOfCopies;
        System.out.println("The total cost is: " + " $"+ totalAmount);  
    } else if (numberOfCopies >= 300 && numberOfCopies <= 499) {
        cost = 0.06 / numberOfCopies;
        subtotal = numberOfCopies * cost;
        totalAmount = subtotal * numberOfCopies;
        System.out.println("The total cost is: " + " $" + totalAmount);
    } else if (numberOfCopies >= 200 && numberOfCopies <= 299){
        cost = 0.07 / numberOfCopies;
        subtotal = numberOfCopies * cost;
        totalAmount = subtotal * numberOfCopies;
        System.out.println("The total cost is: " + " $" + totalAmount);
    } else if (numberOfCopies >= 100 && numberOfCopies <= 199) {
        cost = 0.08 / numberOfCopies;
        subtotal = numberOfCopies * cost;
        totalAmount = subtotal * numberOfCopies;
        System.out.println("The total cost is: " + " $" + totalAmount);
    } else if(numberOfCopies >= 1 && numberOfCopies <= 99) {
        cost = 0.10 / numberOfCopies;
        subtotal = numberOfCopies * cost;
        totalAmount = subtotal * numberOfCopies;
        System.out.println("The total cost is: " + " $" + totalAmount);
    } else if(numberOfCopies == 0) {
        System.out.println("Cannot compute cost of 0 copies");
    }
}

}

0 Answers0