出于某种原因,这种转换真的让我头疼。我可以在纸上和头脑中进行转换,但是当我尝试用Java编写它的作业时,它真的让我感到困惑。分配是让用户输入一个以千克为单位的数字并编写一个程序,上面写着,这是一行上多少磅,这是另一行上多少盎司。转换一般搞砸了我,但我不确定这是否正确。我需要在任何地方使用类型转换吗?
import acm.program.*;
public class KilogramsToPoundsAndOunces extends ConsoleProgram {
public void run(){
println("This programs converts kilograms into pounds and ounces.");
double kilo = readDouble("Enter the kilogram value: ");
double totalOunces = (kilo * POUNDS_PER_KILOGRAM) * OUNCES_PER_POUND;
int totalPounds = totalOunces % OUNCES_PER_POUND;
double leftOverOunces = totalOunces - (totalPounds * OUNCES_PER_POUND);
println(totalPounds + "lbs" + ".");
println(leftOverOunces + "ozs" + ".")
}
private static void POUNDS_PER_KILOGRAM = 2.2;
private static void OUNCES_PER_POUND = 16;
}
答案 0 :(得分:6)
您需要为常量定义数值数据类型:
private static double POUNDS_PER_KILOGRAM = 2.2;
private static int OUNCES_PER_POUND = 16;
还需要将totalPounds
强制转换为int
进行编译:
int totalPounds = (int) (totalOunces % OUNCES_PER_POUND);
虽然应该:
int totalPounds = (int) (totalOunces / OUNCES_PER_POUND);
(见@Kleanthis答案)
答案 1 :(得分:1)
首先,全局变量POUNDS_PER_KILOGRAM
和OUNCES_PER_POUND
是变量,因此没有返回类型(你让它们“返回”为空)。
体型:
private final double POUNDS_PER_KILOGRAM = 2.2;
答案 2 :(得分:1)
我认为程序出错的地方是:
int totalPounds = totalOunces % OUNCES_PER_POUND;
double leftOverOunces = totalOunces - (totalPounds * OUNCES_PER_POUND);
您会看到模数运算符在您获得尽可能多的完整数量后,不会返回总磅数,而是返回剩余的盎司数。例如
int leftoverOunces = totalOunces % OUNCES_PER_POUND;
和
int totalPounds = (int)(totalOunses/OUNCES_PER_POUND);
应该能为您带来正确的结果。