Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Math Logic Error

Status
Not open for further replies.

tberger1

MIS
Sep 12, 2006
16
US
I am writing a program that based on what you enter will determine how much your change will be - it then displays the total of each coin.

The problem is my math - the dimes are not computing right so it gives back more nickles then necessary. Can someone set me straight here. I think other than that it fine.

Here is the code:

import java.util.Scanner;
import java.text.NumberFormat;
import java.util.Locale;

/**
Computes the amount of, listed by coin type, to be returned from a dollar.
*/
public class Change {

public static void main(String[] args) {
// Make a Scanner to read data from the console
Scanner console = new Scanner(System.in);

// Read the cost of the item
System.out.println("Enter price of item");
System.out.print("(from 25 cents to a dollar, in 5-cent increments): ");
int cost = console.nextInt();
int change = 100 - cost;
int quarters = change / 25;
int remainder = change % 25;
int dimes = remainder / 10;
int nickles = remainder / 5;

System.out.printf("Your item cost %d cents %n", cost);
System.out.printf("Your change is %d cents %n", change);
System.out.println("The coins you will receive are:");
System.out.println("Quarters ");
System.out.println(quarters);
System.out.println("Dimes ");
System.out.println(dimes);
System.out.println("Nickles ");
System.out.println(nickles);

}

}
 
You start well with the quarters:
Code:
        int quarters = change / 25;
        int remainder = change % 25;
        int dimes = remainder / 10;
        int nickles = remainder / 5;
but don't substract the value of dimes from the remainder:
Code:
        int quarters = change / 25;
        int remainder = change % 25;
        int dimes = remainder / 10;
        int remainder = remainder % 10;
        int nickles = remainder / 5;
Funny coin names - I hope I understood it right.


seeking a job as java-programmer in Berlin:
 
That should be
Code:
remainder = remainder % 10;

not
Code:
int remainder = remainder % 10;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top