-1

In a solution to an exercise in the Book Art and Science of Java I had to write a program that converts Kilograms into the corresponding values in Pounds and Ounces. I wrote the program but when I try to convert say 1kg, the result the program gives me is: 1 kg = 2 pounds and 3.200000000000006 ounces

Now my constants are 2.2 pounds per kg and 16 ounces per pound so 3.2 ounces is correct. But not with so many 0's and that 6 at the end freaks me out.

Anyone know why this happens and how it can be solved? Thank you!

Here's the code:

/*
* File: KgsLibras.java
* Program that converts kilograms in pounds and ounces.
*/

import acm.program.*;

public class KgsLibras extends ConsoleProgram {
public void run () {
    println ("This program will convert kilograms in pounds and ounces");
    double kgs = readDouble ("Insert kgs value: ");
    double libras = kgs * LIBRAS_POR_KG;
    double oncas = (libras - (int)libras) * ONCAS_POR_LIBRA; 
    println ((int)libras + " libras" + " e " + oncas + " Onças.");
    }
private static final double LIBRAS_POR_KG = 2.2;
private static final int ONCAS_POR_LIBRA = 16;
}
4

2 回答 2

2

That's just a consequence of how floating point works - literally thousands of other references to these issues here on SO alone. The short version is that not all numbers can be represented exactly using floating point numbers, which leads to oddities like the one you're seeing. This document should teach you all you should know about floating point.

In the mean time you can use format to get printf-like formatting options:

System.out.format ("%.0f libras e %.2f Onças.\n",libras,oncas);

or if you have to use that specific println method, use String's format:

println(String.format ("%.0f libras e %.2f Onças.",libras,oncas) );
于 2013-03-30T22:12:04.283 回答
0

You can do something like this:

String libras = String.format("$%.2f", VALUE); //For example..

Then, printing libras will suits your needs.

Regarding of your question about Why your program prints it that way, @fvu was faster than me :)

于 2013-03-30T22:11:22.450 回答