0.05 Result Shows 4 Pennys Instead of 1 Nickel [duplicate] - java

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
This is a problem that wants me to read a double value and determine the fewest number of bills and coin needed to represent the amount.
I'm getting a weird result. I put 5.05 as the moneytotal, and I'm getting 4 pennies when it should be 1 nickel.
I think its a rounding issue but I can't see how to change it when it the problem states to use double.
Scanner scan=new Scanner(System.in);
double moneytotal, ten, five, one, quarters, dimes, nickels, pennies;
System.out.println("Input number!");
moneytotal=scan.nextDouble();
ten= moneytotal % 10;
System.out.println((moneytotal -ten)/10 + " Ten Dollar
Bills.");
five=ten% 5;
System.out.println(((ten - five)/5) + " Five Dollar Bills.");
one = five % 1;
System.out.println((five - one) + " One Dollar Bills.");
quarters = one % 0.25;
System.out.println(((one - quarters)*4) + " Quarters.");
dimes= quarters % 0.10;
System.out.println(((quarters - dimes)*10) + " Dimes.");
nickels=dimes % 0.05;
System.out.println(((dimes - nickels)*20) + " Nickels.");
pennies=nickels % 0.01;
System.out.println(((nickels - pennies) * 100)+ " Pennies.");
Actual result:
input > 5.05
5 Ten Dollar bills.
0 5 Dollar bills.
0 1 dollar bills.
0 quarters.
0 dimes.
0 nickels.
4 pennies.

Calc it as int not double because you can meet the problem regarding of the type changed.
In your code, monytotal % 10 is not 0.5 because 10 is int and % is not good for double. I think the result would be different by language.
Anyway, There is more perfect way as following:
int moneytotaln = moneytotal * 100
ten= moneytotaln % 1000;
System.out.println((moneytotaln -ten)/1000 + " Ten Dollar
Bills.");
// ...

Related

Splitting units base of a number and separating remainders

I am trying to split a number of a base then separating the two numbers to get different outputs. (Keep in mind I just edited, my answer is the solution). This is left here so people that have a similar problem can find a solution. Thank you all!
So this is the idea:
If number >= 10 && of base 10
Then give me discounted price on 10 units
if number <= 0 && not base 10
Then add the discount for the number which has 10 units in it and the remainder without the discount (let's say 100% for simplicity sake of the numbers)
So to make a practical example
If I order 25 units of x (at $1 each) and 15 units (at $1 each) of y the price will be:
x 20 units = $0
x 5 units = $5 total
y 10 units = $0
y 5 units = $5 total
This is a bit tricky and this is what I got so far:
double discountedmNI = (mNI - ((mNI/100)*10)) * mNIC;
double discountedmNIP = mNI - ((mNI/100)*10);
if(mNIC >= 10 && mNIC % 10 == 0){
System.out.println("mNI " + discountedmNIP + " " + mNIC);
System.out.println(discountedmNI);
}
else if (!mNIC % 10 == 0){
System.out.println("mNI " + mNI + mNIC);
System.out.println(mNI * mNIC);
}
I don't think I am defining separate the 10 units right
Thank you all!
I hope I understood you right. I get that you want to calculate a total price that consists of two elements: the price for non-discounted items and a price for discounted items.
// The following three values are just example assumptions.
float discountInPercent = 100.0f;
float itemsOrdered = 5004.0f;
float itemPriceNormal = 5.0f;
// Here the price for one discounted item gets calculated.
// Please remember that the discount is given in percentage.
float itemPriceDiscounted = itemPriceNormal * ((100.0f - discountInPercent) / 100.0f);
// Calculate the count of items that get discounted and those that
// will get priced normally.
float itemsDiscounted = Math.floor(itemsOrdered / 10.0f);
float itemsNotDiscounted = itemsOrdered % 10;
// Finally calculate the two elements of the total price and sum it up.
float priceDiscounted = (itemsDiscounted * itemPriceDiscounted);
float priceNormal = (itemsNotDiscounted * itemPriceNormal);
float totalPrice = priceDiscounted + priceNormal;
System.out.println("Price discounted: %.2f" + priceDiscounted);
System.out.println("Price non-discounted: %.2f" + priceNormal);
System.out.println("Price total: %.2f" + totalPrice);
EUREKA!
double discountedmNIP = mNI - ((mNI/100)*10);
int mNIC2 = (mNIC % 10);
double mNIC2disc = (mNI * mNIC2);
double discountedmNI = (mNI - ((mNI/100)*10)) * (mNIC - mNIC2);
if(mNIC >= 10){
System.out.println(discountedmNIP + " " + (mNIC - mNIC2) + " " + discountedmNI );
System.out.println(mNI + " " + mNIC2 + " " + mNIC2disc);
}
else{
System.out.print(mNI + " " + mNIC);
System.out.print(mNI * mNIC);
}
double sum = (mNI + discountedmNI + discountedRh + rH);
System.out.println('\t');
System.out.println("Total order cost " + sum);
All I need to do is to take the units % 10 which will divide the left side integer or double by the right side (left side input from user)
and will give me the remainder when I do that variable subtracted to the original variable!
Again, this small step took me a whole night to figure it out, and is simple indeed. This is for a class, and if you are in that class and you are reading (even though you might have to dig a little to find what assignment is this one), I would just like to tell you this is what's fun about programming! I am not being sarcastic I really love these type of problems!
Signed:
That foreign guy;
EUREKA again!
Enjoy!

Converting Double to 2 Decimal Places [duplicate]

This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 6 years ago.
I have a code where an individual orders a certain number of coffees and coffee shots in each cup, and the program calculates the total price (purchasePrice). However, when i output the purchase price as a double, it only outputs a number with 1 decimal place. How can i change it to output with 2 decimal places.
double purchasePrice = 0;
for (counting = 0; counting < coffeeCups; counting++) {
System.out.println("Cup " + (counting + 1) + " has " + coffeeShots[counting] + " shot(s) and will cost $" + (2 + coffeeShots[counting]) + "\n");
purchasePrice+= 2 + (coffeeShots[counting]);
}
System.out.println(coffeeCups + " coffees to purchase.");
System.out.println("\nPurchase price is $" + purchasePrice + ".");
Please refer to Decimal Format
// 2 places of decimal
DecimalFormat formatter = new DecimalFormat( "#.00" );
System.out.println(formatter.format(1.23)); // 1.23
System.out.println(formatter.format(1)); // 1.00
System.out.println(formatter.format(1.234)); // 1.23

Trouble with the converting units

I am having a hard time understanding how to convert amounts such as $1.17 into this output:
1 dollar,
1 dime,
1 nickel,
2 pennies.
I need to use if statements which I can figure out but, the problem i am having is trying to get the change amounts to display correctly. Here is my code. I`m a visual learner so if you start me in the right direction that would be helpful.
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an amount in double, for example 11.56: " );
double number = input.nextDouble();
System.out.println("Your amount " + number + " consists of ");
int Dollars = (int) (number);
int Quarters = Dollars / 25;
if (number == 1) {
System.out.print("1 dollar ");
}
else if (number > 1) {
System.out.print((int)Dollars + " dollars ");
}
if (number == 0) {
System.out.println("");
}
System.out.print( Quarters + " Quarters ");
}
}
You will probably want to use the modulus operator %. It is used with 2 numbers and returns the remainder of a divided by b where a is the left hand assignment and b is the right hand represented like a%b.
Example:
11%2=1 explanation: 5*2 = 10, 11-10 = 1
.66%.25=.16 explanation: 2*.25 = .5, .66-.5=.16
Start with a simple problem where you only have 2 types of coins, say 8¢ or $0.08.
double monies = .08;
int numNickles = (int)(monies/.05) = 1 // one nickle
monies = monies % .05; // or you can write as monies %=.05;
// monies value should now be .03
int numPennies = (int)(monies/.01) = 3 // three pennies
A much simpler approach than using modulus is to calculate the units of measurement in top-down fashion (from the highest to the lowest) and keep deducting them from the total already converted into the lowest unit.
A lot of libraries use this approach with units of time as well i.e. converting a time span into hours, minutes and seconds. Here's the same approach for currency. I've added inline comments to explain the code as best as possible.
// Scan the amount
Scanner scanner = new Scanner(System.in);
System.out.print("Enter amount: ");
double amount = scanner.nextDouble();
scanner.close();
// convert into cents
int cents = (int) (amount * 100);
// get dollars
int dollars = cents/100;
// cents left after dollars
cents = cents - dollars*100;
// get quarters
int quaters = cents/25;
// cents left after quarters
cents = cents - quaters*25;
// get dimes
int dimes = cents/10;
// cents left after dimes
cents = cents - dimes*10;
// get nickels
int nickels = cents/5;
// cents left after nickels
cents = cents - nickels*5;
// leftover cents are pennies
int pennies = cents;
Now, just build the output message with a StringBuilder as
StringBuilder msg = new StringBuilder("You have:");
if (dollars > 0) {
msg.append(" ").append(dollars).append(" dollar").append(dollars > 1 ? "s" : "");
}
if (quaters > 0) {
msg.append(" ").append(quaters).append(" quarter").append(quaters > 1 ? "s" : "");
}
if (dimes > 0) {
msg.append(" ").append(dimes).append(" dime").append(dimes > 1 ? "s" : "");
}
if (nickels > 0) {
msg.append(" ").append(nickels).append(" nickel").append(nickels > 1 ? "s" : "");
}
if (pennies > 0) {
msg.append(" ").append(pennies).append(" pennie").append(pennies > 1 ? "s" : "");
}
System.out.println(msg);
Output :
Enter amount: 1.17
You have: 1 dollar 1 dime 1 nickel 2 pennies
Enter amount: 12.99
You have: 12 dollars 3 quarters 2 dimes 4 pennies

Math line only running once in a loop

this is my first interaction with this site, I have heard good things and I hope I can find the answer that I am looking for. I am learning Java and using the Eclipse IDE in a computer science class at my high school and I came across a problem that neither my teacher or I can solve. Here are the instructions.
"The German Mathematician GottfriedLeibniz developed the follow method to approximate the value of π.
π/4 = 1 - 1/3 + 1/5 - 1/7 + ...
Write a program that allows the user to specify the number if iterations used in this approximation and displays the resulting value."
Now the code.
import java.util.Scanner;
public class GottfriedLeibnizPi {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter how many iterations you want to go to: ");
int iterations = reader.nextInt();
double pi = 0;
if (iterations >= 0) {
for (int count = 0; count <= iterations - 1; count++) {
System.out.println("pi: " + pi + " count: " + count); //debug statement to show pi and count before running the code
if (count % 2 == 0) {
pi = pi + (1 / (1 + (2 * count))); // first to run. starts at pi + 1 and every other loop adds 1/(1+2n)
} else {
pi = pi - (1 / (1 + (2 * count))); // first to run. starts at pi - 1/3 and every other loop subtracts 1/(1+2n)
}
System.out.println("pi: " + pi + " count: " + count + "\n"); //debug statement to show pi and count after running the code
}
pi = pi * 4; //obtains the true value of pi
System.out.println("The value of pi after " + iterations + " iterations is " + pi);
} else {
System.out.println("Please enter a non-negative number");
}
}
}
Here is the output with the the debugging statements if I enter five at the prompt.
Enter how many iterations you want to go to: 5
pi: 0.0 count: 0
pi: 1.0 count: 0
pi: 1.0 count: 1
pi: 1.0 count: 1
pi: 1.0 count: 2
pi: 1.0 count: 2
pi: 1.0 count: 3
pi: 1.0 count: 3
pi: 1.0 count: 4
pi: 1.0 count: 4
The value of pi after 5 iterations is 4.0
My math says that answer should be 3.3396... but the math in my loop does not appear to run more than once. I have not found anything on here that is close to my problem, does anyone know what is wrong?
The problem seems to be a roundoff caused by integer division. Try replacing the relevant part of your code with this:
if(count % 2 == 0){
pi = pi + (1 / (1 + (2.0 * count))); // first to run. starts at pi + 1 and every other loop adds 1/(1+2n)
}
else{
pi = pi - (1 / (1 + (2.0 * count))); // first to run. starts at pi - 1/3 and every other loop subtracts 1/(1+2n)
}
Since "1" in the numerator is an integer, and "(1 + (2*Count))" in the denominator is also an integer, you will get integer division which truncates any remainder from the division. Since the denominator in this case is going to be greater than or equal to 1, 1/(positive integer greater than 1) will always result in 0 in integer division. By adding a decimal to one of the integers Java will treat it as a double and not perform integer division.
So actually, there is no problem with the execution of the lines. When I run the code with the above changes I get the same answer as given by your teacher.
The value of pi after 5 iterations is 3.3396825396825403
int/int gives an int type, by which you loose the fractional part of the divison ( 3/2 gives 1 ) . So you need -
pi = pi + (1.0 / (1.0 + (2 * count))); // Notice the 1.0
Similarly in the other case too.
In both the cases of:
pi = pi + (1 / (1 + (2 * count))); // (1 / (1 + (2 * count))) everything here is an int so, so you are losing . and everything after .
change it to
pi = pi + (1d / (1 + (2 * count)));
iterations=int(input('enter no of iterations'))
adding = 0
for i in range(1, iterations + 1, 2):
if i % 4 == 1:
adding += 1/i
else:
adding -= 1/i
pi = 4 * adding

Java problem solving. Is this one right?

Merry Christmas everyone. I do have a question before Santa arrives.
I'm new with Java, so i'm skimming through my Java book and I'm doing the exercises on my first chapter.
Here's the question,
"Write and application that determines the value of the coins in a jar and prints the total in Dollars and Cents. Read integer values that represent the number of quarters, dimes, nickels and pennies."
I actually did this program. But I wonder if I did it right.
public class PP28 {
public static void main(String[] args) {
// cents = pennies.
double quarters = 0.25 * 40;
double dimes = 0.1 * 200;
double nickels = 0.05 * 400;
double pennies = 0.01 * 150;
int total;
int cent;
total = (int) quarters + (int) dimes + (int) nickels + (int) pennies;
cent = 100 % total;
System.out.println(total+" dollars and "+cent+" cents");
}
}
It compiles and runs fine. Also, I wonder if this is mathematically right? Should I get 49 cents that is almost equivalent to 51.(5)$? Because all quarters, dimes, nickels and pennies has the sum of 51.5 dollars.
I would avoid using a floating point type for this due to rounding errors.
Here is a good article explaining the issue (What Every Computer Scientist Should Know About Floating-Point Arithmetic).
Use integers to get the count in cents.
Something like this:
integer quarters = 25 * numOfQuarters;
You can get the dollar amount by diving with 100.
Oded's answer is definitely one to implement. Use integers.
You have another problem however: cent = 100 % total;
This code is not doing what you think it's doing.
Because total is an integer and is summed like this:
total = (int) quarters + (int) dimes + (int) nickels + (int) pennies;
Your result is 51. That's 51 dollars even. You lost all of the information on fractional dollars by converting the double values (quarters, dimes, nickels and pennies) to integers. If the value of quarters would have been 10.25, then (int) quarters would be 10.
Now, you are trying to get the number of leftover cents using cent = 100 % total; This gives you the integer remainder of 100 / total. In your case 100 / 51. The remainder leftover is 49 which you stored in 'cent'. It just happened in your example to be close to the correct value. This is why your answer was incorrect, not rounding.
All that said, you should STILL be using integers for all of your values.
It is easier to work on one representation, for example cents, and then later translate it into dollars. Oded's comment about floating point rounding errors are correct.
I do find it strange that you convert pennies into an integer when the value is 1.5, this doesn't seem correct. Something like this can be done instead:
int quarters = 25 * 40;
int dimes = 10 * 200;
int nickels = 5 * 400;
int pennies = 1 * 150;
int sum = quarters + dimes + nickels + pennies;
int dollars = sum / 100;
int cents = sum % 100;
When printing the values of dollars and cents I get 51 dollars and 50 cents exactly.
In addition to the problems mentioned about, the problem says read the number of quarters, dimes, nickels and pennies. That means read from a file, not have hard-coded as constants.
Also, the monetary values of quarters, dimes, nickels and pennies are unlikely to change anytime soon. They should be declared as static final variables:
class PP28 {
final int QUARTER = 25;
...

Categories