出于某种原因,这种转换真的让我头疼.我可以在纸上和头脑中进行转换,但是当我尝试用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;
}
Run Code Online (Sandbox Code Playgroud)
您需要为常量定义数值数据类型:
private static double POUNDS_PER_KILOGRAM = 2.2;
private static int OUNCES_PER_POUND = 16;
Run Code Online (Sandbox Code Playgroud)
还totalPounds需要强制转换int为编译:
int totalPounds = (int) (totalOunces % OUNCES_PER_POUND);
Run Code Online (Sandbox Code Playgroud)
虽然这应该是:
int totalPounds = (int) (totalOunces / OUNCES_PER_POUND);
Run Code Online (Sandbox Code Playgroud)
(见@Kleanthis答案)
| 归档时间: |
|
| 查看次数: |
3743 次 |
| 最近记录: |