0

出于某种原因,这种转换真的让我很头疼。我可以在纸上和头脑中进行转换,但是当我尝试用 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; 
}   
4

3 回答 3

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 答案)

于 2012-10-18T22:45:21.473 回答
1

首先,全局变量POUNDS_PER_KILOGRAMOUNCES_PER_POUND变量是变量,因此没有返回类型(你让它们“返回”无效)。

更喜欢:

private final double POUNDS_PER_KILOGRAM = 2.2;
于 2012-10-18T22:46:00.547 回答
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);

这应该会给你正确的结果。

于 2012-10-18T22:55:33.490 回答