【问题标题】:count++ and ++count, when to use which? [duplicate]count++ 和 ++count,什么时候用哪个? [复制]
【发布时间】:2014-02-06 20:17:33
【问题描述】:

所以我遇到了这个小增量方法

从高中开始就习惯了这种方式

char[] NewArray = new char[5] //I forgot how to declare an array

string temp;

console.writeline("Enter 5 letters)

for (i=0; i<5;i++)
{
   NewArray[i] = console.readline()
}

现在基于此代码

我声明了一个包含 5 个“空格”的 char 数组,然后我向控制台输出一条消息,要求用户输入 5 个值

所以 i = 0,readline 例如c

因此在 console.readline 语句之前,i=0,然后它继续执行 for 循环,然后返回到循环的开头,在再次执行 console.readline 之前递增 i = 1

这与“++i”有何不同,“++i”在 for 循环中会做什么?

【问题讨论】:

    标签: c# increment


    【解决方案1】:

    count++ 是后增量,++count 是前增量。假设您写count++ 表示执行此语句后值增加。但如果++count 值在执行此行时会增加。

    【讨论】:

      【解决方案2】:

      ++x 是前置增量,x++ 是后置增量,第一个 x 在使用前递增,第二个 x 在使用后递增。

      如果您编写 x++ 或 ++x,它们是相同的;。 如果x=5; x++=6++x=6

      但是如果你执行x++ + x++(5 +6) 它会给你不同的结果将是11

      但是如果你执行x++ + ++x(5 +7) 它会给你不同的结果将是12

      但是如果你执行++x + ++x(6 +7) 它会给你不同的结果将是13

      【讨论】:

        【解决方案3】:

        在 for 循环中没有什么不同。因为如果您的条件为真,则 for 循环将执行一次,然后它会执行您的步骤。所以这个:

        for(int=0; i<4; i++)
        

        等于:

        for(int=0; i<4; ++i)
        

        你可以认为它就像:

        i++;
        

        和;

         ++i;
        

        【讨论】:

          【解决方案4】:

          作为附加信息。这就是您可以想象的两种不同运算符的实现方式:

          前缀:

          int operator++ () { 
              //let "this" be the int where you call the operator on
              this = this + 1;
              return this;
          }
          

          后缀:

          int operator++ (int) { //the dummy int here denotes postfix by convention
              //let "this" be the int where you call the operator on
              int tmp = this; //store a copy value of the integer (overhead with regards to prefix version)
              this = this + 1; //increment
              return tmp; //return the "pre-incremented" value
          }
          

          【讨论】:

            猜你喜欢
            • 2014-06-09
            • 2011-02-12
            • 2015-03-03
            • 2011-03-01
            • 2010-09-08
            • 2018-05-09
            相关资源
            最近更新 更多