0

我正在尝试编写一个将公斤转换为磅和盎司的程序。如果用户输入 100 公斤,我期望的结果是 220 磅和 7.4 盎司。

我得到了正确的磅值,但我的问题是得到了正确的盎司值。我不知道我错过了什么。此外,当我计算盎司值时,我如何向程序指定我只想要百分之一的答案。例如我只想要 7.4 盎司而不是 7.4353?

import acm.program.*;
public class KilogramsToPoundsAndOunces extends ConsoleProgram {
public void run() {

    println("This program converts Kilograms into Pounds and Ounces.");

    int kilo = readInt("please enter a number in kilograms: ");

    double lbs = kilo * POUNDS_PER_KILOGRAM; 

    double oz = lbs * OUNCES_PER_POUND; 

    double endPounds = (int) oz / OUNCES_PER_POUND;

    double endOunces =  oz - (endPounds * OUNCES_PER_POUND); 

    println( endPounds + " lbs " + endOunces + "ozs");




}
private static final double POUNDS_PER_KILOGRAM = 2.2;
private static final int OUNCES_PER_POUND = 16;
}
4

3 回答 3

1

Cases where you need exact decimal value; its better to use BigDecimal data type instead of double.

The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. link

BigDecimal provides methods to round the number to given value.

于 2012-11-08T06:04:10.870 回答
1

最简单的方法是在那里使用System.out.printf和格式化输出:

System.out.printf("%d lbs %.1f ozs", endPounds, endOunces);

如果你不能使用System.out.printf,你仍然可以使用String#format来格式化输出:

println(String.format("%d lbs %.1f ozs", endPounds, endOunces));
于 2012-11-08T05:23:26.943 回答
0

用于DecimalFormat以所需格式打印小数位,例如

    DecimalFormat dFormat = new DecimalFormat("#.0");
    System.out.println( endPounds + " lbs " + dFormat.format(endOunces) + " ozs");

如果要四舍五入到小数点后一位,则将数字乘以 10,四舍五入,然后再除并打印如下:

double roundedOunces = Math.round(endOunces*10)/10.0;
DecimalFormat dFormat = new DecimalFormat("#.0");
System.out.println( endPounds + " lbs " + dFormat.format(roundedOunces) + " ozs");

编辑:

试试这个四舍五入:

  double roundedOunces = Math.round(endOunces*10)/10.0;. 

不四舍五入:

  double roundedOunces = endOunces*10/10.0;
于 2012-11-08T05:19:56.980 回答