如何在 Java 中编写数学公式

How to write a mathematical formula in Java

我正在尝试找出一种将千克(由用户输入)转换为英石和磅的方法。

例如:

用户输入的重量为 83.456 公斤,乘以 2.204622 换算为磅 = 184 磅,将 184 磅除以 14 换算为英石 = 13.142 英石。

用前两位数字 (13) 表示石头,将余数除以 14 得到磅,0.142(这是余数)x 14 = 1.988 磅,或者有其他方法可以得到这个结果吗?

因此此人的体重为 13 英石和 2 磅(四舍五入)。

这是我目前所拥有的(有效的):

pounds = kgs*2.204622;  
System.out.printf("Your weight in pounds is: %.0f" , pounds);
System.out.print(" Ibs\n");
stone = pounds / 14
//Can't figure out how to finish the formula in code

我假设您在此处使用它们之前声明了 poundsstone(即使用 float pounds;double pounds;float pounds = 某些东西),否则代码将无法编译。

一种方法是分两步完成,如下所示:

double kg = 83.456;
double pounds = kg * 2.204622;

double stonesWithDecimal = pounds / 14;

int stone = (int) stonesWithDecimal; // Strip off the decimal
long poundsWithoutStone = Math.round((stonesWithDecimal - stone) * 14); // Take the fractional remainder and multiply by 14
System.out.println("Stone: " + stone + "\nPounds: " + poundsWithoutStone);

Andreas 的建议肯定更清晰,但我想同时介绍这两个建议,因为我不确定您对在编程中使用模数的熟悉程度。 这是该建议的一种实现,尽管您可以在处理数据类型方面采用几种不同的方式(Math.round 想要 return a long):

double kg = 83.456;
double pounds = kg * 2.204622;

int stone = (int) pounds / 14;
pounds = (double) Math.round(pounds %= 14);

System.out.println("Stone: " + stone + "\nPounds: " + pounds);

如果您正在寻找可扩展的现成库,您可以考虑免费和开源库 UnitOf

它为 Mass 提供了 30 多种开箱即用的转换。

示例

double kgFromPound = new UnitOf.Mass().fromPounds(5).toKilograms(); 

double poundFromKg = new UnitOf.Mass().fromKilograms(5).toPounds(); 

希望对您有所帮助!

正确的解决方案早轮。这是 :

建议的代码
double kgs = 83.456;
long pounds = Math.round(kgs*2.204622);
System.out.println("Your weight is " + pounds / 14 + " stone and " + pounds % 14 + " pounds");

输出

Your weight is 13 stone and 2 pounds

如果您改用 69.853 公斤,您会得到

Your weight is 11 stone and 0 pounds

但如果你不早点到场,这就是事情变得危险的地方。


(当前接受的) 中的两个解决方案都是错误的,因为它们在错误的时间舍入。你必须早点轮到是有原因的。

如果你在这两个解决方案中改为使用 69.853 公斤,你会得到

Solution 1:
  Stone: 10
  Pounds: 14

Solution 2:
  Stone: 10
  Pounds: 14.0

两者显然都不正确,因为 Pounds 不应该是 14,也就是 1 石头。

如果您打印没有舍入的值,舍入错误的原因就很明显了

double kgs = 69.853;
double pounds = kgs*2.204622;
System.out.println(pounds + " lbs = " + pounds / 14 + " stone and " + pounds % 14 + " pounds");

输出

153.99946056599998 lbs = 10.999961468999999 stone and 13.999460565999982 pounds