为什么此代码段显示答案为6? [英] Why does this snippet display the answer as 6?

查看:115
本文介绍了为什么此代码段显示答案为6?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个同学问了这个问题,我想确定我告诉他正确的答案。基本上下面的代码(确实显示6作为答案)困惑他,当它得到MessageBox.Show((i - )。ToString())。

A classmate of mine asked this question, and I wanted to be sure that I was telling him the correct answer. Essentially the code below (which does indeed display "6" as the answer) confused him when it got to MessageBox.Show((i--).ToString());.

我的解释是递减操作(i--)实际上没有发生,因为它被传递给MessageBox对象的.Show方法。因此,它显示6,因为它实际上并没有将该值减少1.

My explanation was that the decrement operation (i--) isn't actually taking place, since it is being passed to the .Show method of the MessageBox object. So it displays 6 because it's not actually reducing that value by 1.

这是正确的解释吗?我从来没有试图抛出inc / dec操作,同时还显示值的同时,所以我不知道我的推理是否正确。谢谢!

Is this the correct explanation? I've never tried to throw inc/dec operations while also displaying values at the same time, so I'm not sure if my reasoning on this is correct. Thanks!

        int i = 6;            // I starts as 6...
        if (i >=4 )           // Then the check to see if i >= 4 is TRUE...
        {
            if( i == 5)       // The check to see if i == 5 is FALSE...
            {
                MessageBox.Show(i.ToString()); 
            }
            else
            {
                MessageBox.Show((i--).ToString());  // ****
            }
        }
        else 
        { 
            MessageBox.Show((i++).ToString());
        }


推荐答案

i - 返回i的值,并返回递减前的值。

i-- returns the value of i and returns the value before the decrement.

您应该按照词汇顺序)。

You should read it logically in the lexical order (as was intended by the creators) :

puts the value
and then decrements

如果是6之前,则返回6(打印),即使在i的值为5之后。

If it's 6 before, it returns 6 (which is printed) even if just after the value of i is 5.

请注意, - i 递减并返回递减的值。

Note that --i decrements and returns the decremented value.

这篇关于为什么此代码段显示答案为6?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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