为什么这个if语句会出现这个输出? [英] Why does this output occur for this if statement?

查看:110
本文介绍了为什么这个if语句会出现这个输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

double j = 128.22, k = 129.22;
if ((j++) == k)
    j += 10;
k += 10;
System.out.println(j);
System.out.prinkln(k);





输出为129.22

139.22



为什么它将if语句读为false?我正在教编程1,我已经问了我所有的资料,并且无法真正得到答案。



The output is 129.22
139.22

Why does it read the if statement as false? I'm teaching programming 1 and I've asked all my sources, and can't really get an answer.

推荐答案

查看之间的区别。

Look into the difference between.
if ((j++) == k)     // postfix operator






and

if ((++j) == k)  // prefix operator





对于后缀运算符,在j递增之前进行比较。

(128.22 == 129.22)



对于前缀运算符,在j递增后进行比较。

(129.22 == 129.22)



[更新]

正如谢尔盖所​​说,在浮点类型上使用++运算符是很不寻常的。浮点有点复杂,可能很难解释。

当我们触及这个主题时,我添加了两个链接以供进一步阅读:

查看此CP的解决方案5题。 浮动数字的问题 [ ^ ]



作为一名数学/编程老师,您可能会发现这篇文章很有趣。 每个计算机科学家应该知道的关于浮点运算的内容 [ ^ ]



祝你好运。



For the postfix operator the comparison is made BEFORE j is incremented.
(128.22 == 129.22)

For the prefix operator the comparison is made AFTER j is incremented.
(129.22 == 129.22)

[Update]
As Sergey mentioned, it is pretty unusual to use the ++ operator on floating point types. Floating points are a bit complicated and can be tricky to explain.
As we touched on this subject I add two links for further reading:
Look at Solution 5 for this CP question. The problem with floating numbers[^]

As a math/programming teacher, you might find this article interesting. What Every Computer Scientist Should Know About Floating-Point Arithmetic[^]

Good luck with your teaching.


这篇关于为什么这个if语句会出现这个输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆