开发者

need help with some basic java

I'm doing the first chapter exercises on my Java book and I have been stuck for a problem for a while now. I'll print the question,

prompt/read a double value representing a mon开发者_运维问答etary amount. Then determine the fewest number of each bill and coin needed to represent that amount, starting with the highest (assume that a ten dollar bill is the maximum size needed). For example, if the value entered is 47,63 (forty-seven dollars and sixty-three cents), and the program should print the equivalent amount as:

  1. 4 ten dollar bills
  2. 1 five dollar bills
  3. 2 one dollar bills
  4. 2 quarters
  5. 1 dimes
  6. 0 nickels
  7. 3 pennies"

etc.

I'm doing an example exactly as they said in order to get an idea, as you will see in the code. Nevertheless, I managed to print 4 dollars, and I can't figure out how to get "1 five dollar", only 7 dollars (see code).

Please, don't do the whole code for me. I just need some advice in regards to what I said. Thank you.

import java.util.Scanner;

public class PP29 {
    public static void main (String[] args) {

        Scanner sc = new Scanner (System.in);

        int amount;
        double value;
        double test1;
        double quarter;

        System.out.println("Enter \"double\" value: ");
        value = sc.nextDouble();

        amount = (int) value / 10;      // 47,63 / 10 = 4. 
        int amount2 = (int) value % 10; // 47 - 40 = 7

        quarter = value * 100;          // 47,63 * 100 = 4736
        int sum = (int) quarter % 100;  // 4763 / 100 => 4763-4700 = 63.

        System.out.println(amount);
        System.out.println(amount2);
    }
}


To get the result for 10 dollar bills you divided by 10.

Now think about how you can use 7 / 5 and 7 % 5.

I'd also advise you not to use doubles for this because representation errors can give you an incorrect result. It would be better to perform this calculation in cents and use only integer arithmetic. An input of "47,63" can be treated as 4763 cents, and a ten dollar bill is 1000 cents.


First, you shouldn't do calculations with floating-point numbers, if possible. There are many tricky details.

For this question it is better to read the monetary value as a double and then convert it to cents as quickly as possible.

double monetaryValue = scanner.nextDouble();
int cents = (int) (monetaryValue * 100.0 + 0.5);

int remaining = cents;
int tenDollars = remaining / 1000;
remaining %= 1000;
int fiveDollars = remaining / 500;
// TODO: continue calculation with remaining ...

I'm sure you will figure out how to continue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜