0

So I was building a program where I take different coins and print out the value into dollars and cents. Since I needed each to be a whole number I did some coding to make it so. My problem is that on certain instances, when running the program, my cents value comes out wrong. EVERYTHING else is correct. I'm assuming this is something to do with converting to an integer and its causing it not to round when certain user input is given. For example, when I enter 10 quarters, 3 dimes, 6 nickels, and 2 pennies, it comes out with 11 cents at the end. I can not figure out the error here.

My full code is below. Can anyone let me know what I did wrong?

    public static void main (String[]args){

    Scanner sc=new Scanner(System.in);
    System.out.print("Enter the number of quarters: ");
    double qs=sc.nextDouble();
    System.out.print("Enter the number of dimes: ");
    double ds=sc.nextDouble();
    System.out.print("Enter the number of nickels: ");
    double ns=sc.nextDouble();
    System.out.print("Enter the number of pennies: ");
    double ps=sc.nextDouble();
    System.out.print("\n");

    double qV=0.25;
    double dV=0.10;
    double nV=0.05;
    double pV=0.01;
    double tQ=qs*qV, tD=ds*dV, tN=ns*nV, tP=ps*pV;
    double totalV=tQ+tD+tN+tP;
    int dollars=(int)totalV;
    double cent=(totalV-dollars)*100;
    int cents=(int)cent;
    
    int tqs=(int)qs;
    int tds=(int)ds;
    int tns=(int)ns;
    int tps=(int)ps;

    System.out.println("You entered "+tqs+" quarters.");
    System.out.println("You entered "+tds+" dimes.");
    System.out.println("You entered "+tns+" nickels.");
    System.out.println("You entered "+tps+" pennies.");
    System.out.print("\n");

    System.out.println("Your total is "+dollars+" dollars and "+cents+" cents.");
    }

2 Answers2

0

Good day,

The right way to get what you wanted is to use Math.round() method as such:

int cents= (int) Math.round(cent);

I would apply the same approach for your dollars value. You may read more about IEEE 754 calculations, here is a good is a good explanation on what is going on under the hood - Is there any IEEE 754 standard implementations for Java floating point primitives?

0

Don't use double at all.

The number of coins is always a whole number. Use int to represent a whole number.

An amount of money can be a whole number if you count the total in cents. Use int.

System.out.print("Enter the number of quarters: ");
int qs=sc.nextInt();
 … etc …

int total = 25*qs + 10*ds + 5*ns + ps;

Now, the number of dollars is the total number of cents divided by 100, and the number of cents is the remainder when dividing the total by 100.

int dollars = total / 100;
int cents = total % 100;
System.out.println("Your total is " + dollars + " dollars and "
                   + cents + " cents.");

This is a lot simpler than having to do the conversions, and the artithmetic is always exact.

J.Backus
  • 1,441
  • 1
  • 6
  • 6