如何用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
安德烈亚斯

正确的解决方案应尽早解决。这是我最初的评论所建议的代码

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

但这就是如果您不及早取舍的话。


Lightning的答案(当前接受的)中的两个解决方案都是错误的,因为它们在错误的时间舍入。您必须尽早进行四舍五入是有原因的。

如果您更改为在这两个解决方案中使用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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章