gpt4 book ai didi

java - 需要帮助将公斤转换为磅和盎司

转载 作者:行者123 更新时间:2023-12-01 07:11:42 25 4
gpt4 key购买 nike

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

最佳答案

您需要为常量定义数字数据类型:

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

关于java - 需要帮助将公斤转换为磅和盎司,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12964880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com