我正在尝试编写一个将千克转换为磅和盎司的程序。如果用户输入 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;
}
最佳答案
最简单的方法是使用 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));
关于java - 公斤 转换为 磅和盎司,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13282882/