I haven't used java in a long while and i'm trying to teach someone the basics and get some practice in for myself. I decided to make a change machine that will give you the amount of Dollars Quaters NIckles etc one of those beginner codes.
This isn't the final code but I just have periodic print statements scattered about to test whether the code is working or not.
// THE CODE OUTPUT
2 dollars and the change is 0.69
2 quaters and the change is 0.18999999999999995
1 dime and the change is 0.08999999999999994
1 nickel and the change is 0.03999999999999994
3 pennies and the change is 0.009999999999999938
// THE QUESTION
It should be 4 pennies instead of 3, I thought of using an if statement like if change > 0.0 then + 1 penny but I feel like that's a brutish way of doing that could cause problems in the future but i'm also trying to keep it as simple as possible.
Is there any other suggestions on how to properly get 4pennies, I believe there's a way to limit the decimal though I don't remember how complex it was.
Thank you in advance and if there are any suggestions to my code please feel free whether it be an easier way to do it or etc.
import java.util.Scanner;
public class changeMachine {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Price");
double price = scan.nextDouble();
System.out.println("Price " + price + "\n");
System.out.println("Cash");
double cash = scan.nextDouble();
System.out.println("Cash " + cash + "\n");
double change = (cash - price);
System.out.println("Change " + change + "\n");
double dollar = 1.00;
double quater = 0.25;
double dime = 0.10;
double nickel = 0.05;
double penny = 0.01;
int dollarAmount = (int)(change / dollar);
change = change % dollar;
System.out.println(dollarAmount + " dollars and the change is " + change);
int quaterAmount = (int)(change / quater);
change = (change % quater);
System.out.println(quaterAmount + " quaters and the change is " + change);
int dimeAmount = (int)(change / dime);
change = (change % dime);
System.out.println(dimeAmount + " dime and the change is " + change);
int nickelAmount = (int)(change / nickel);
change = (change % nickel);
System.out.println(nickelAmount + " nickel and the change is " + change);
int pennyAmount = (int)(change / penny);
change = (change % penny);
System.out.println(pennyAmount + " penny and the change is " + change);
}
}
Aucun commentaire:
Enregistrer un commentaire