简体   繁体   English

int如何在Java数学方程中工作?

[英]How does int work in Java math equations?

I've been reviewing my Java for a class I've taken for the whole year and haven't been doing well on. 我一直在审查我的Java,这是我整年参加的一个课程,并且一直没有取得好成绩。 They have a separate review book called "Be Prepared." 他们有一本名为“准备好”的单独评论书。 I want to see if I get the math behind this line. 我想看看我是否在这一行背后得到了数学。

result = (1 / 2) * n * (n + 1);    // result is 0.0

The thing is, this is basic basic basic. 问题是,这是基本的基本基础。 I need to know if I'm actually getting this. 我需要知道我是否真的得到了这个。 It looks like my like (1/2) is 0.5. 看起来我喜欢(1/2)是0.5。 That cast to an int is 0. That's why the whole thing is 0.0. 转换为int为0.这就是整个事情为0.0的原因。

Am I right? 我对吗?

This book is how you get ready for the AP test. 本书就是你准备AP测试的方法。 Anyone done eimacs who can help? 谁做过eimacs谁可以帮忙?

(1 / 2) will return zero. (1/2)将返回零。 both are integer and as per integer calculation it will return zero. 两者都是整数,按整数计算,它将返回零。

Try 尝试

result = (1.0 / 2) * n * (n + 1);  

Please have a look at : 请看看:


In Java the result of each operation is decided by the higher type involved in calculation. 在Java中,每个操作的结果由计算中涉及的较高类型决定。 It doesn't matter in what type are you assigning the result. 分配结果的类型无关紧要。

for eg 例如

double d = 10/3;

the value of d will be 3.0 only not 3.33. d的值仅为3.0而不是3.33。

Yes, and note that 999 / 1000 will also return 0 . 是的,请注意999 / 1000也会返回0 It's truncation, not rounding down. 这是截断,而不是四舍五入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM