[英]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
我假设您在这里使用它们之前声明了pounds
和stone
(即使用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 希望返回一个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");
Output
Your weight is 13 stone and 2 pounds
如果你改为使用69.853 kgs ,你会得到
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");
Output
153.99946056599998 lbs = 10.999961468999999 stone and 13.999460565999982 pounds
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.