数学方程式如何在Java中运作?

编程入门 行业动态 更新时间:2024-10-27 02:31:32
本文介绍了数学方程式如何在Java中运作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我做这样的事情

int test = 5 + 3 * (4 - 1) / 2;

我得到9.我怀疑这是因为int四舍五入.但是,当我这样做

I get 9. I suspected this was because int rounds down. However, when I do this

float test = 5 + 3 * (4 - 1) / 2;

我也得到9.但是,当我这样做时

I also get 9. However, when I do this

float test1 = 5; float test2 = 4.5; float test = test1 + test2;

测试最终输出9.5.有人可以解释其背后的逻辑吗?为什么在第二个示例中我没有得到9.5?谢谢.

Test finally outputs 9.5. Could someone explain the logic behind this? Why don't I get 9.5 in the second example? Thanks.

推荐答案

在第二个示例中,尽管您正在将结果赋值给float类型的变量,但计算本身仍在执行与第一个示例完全相同. Java不会查看目标变量类型来确定如何计算右侧.特别是,子表达式3 * (4 - 1) / 2会导致4.

In your second example, although you are assigning the result to a variable of type float, the calculation itself is still performed exactly the same way as the first example. Java does not look at the destination variable type to determine how to calculate the right hand side. In particular, the subexpression 3 * (4 - 1) / 2 results in 4.

要解决此问题,可以使用浮点文字而不是所有整数:

To fix this, you can use floating point literals instead of all integers:

float test = 5 + 3 * (4 - 1) / 2.0f;

使用2.0f触发算术表达式的浮点计算.

Using 2.0f triggers floating point calculations for the arithmetic expression.

更多推荐

数学方程式如何在Java中运作?

本文发布于:2023-10-24 08:59:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523511.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方程式   数学   如何在   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!