代码之家  ›  专栏  ›  技术社区  ›  santosh singh

增量运算符(++)问题:为什么我得到错误的输出?

c#
  •  4
  • santosh singh  · 技术社区  · 15 年前

    我有一个简单的c#控制台应用程序,但我得到了错误的输出为什么?

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication11
    {
    class Program
    {
        static void Main(string[] args)
        {
            int i = 100;
            for (int n = 0; n < 100; n++)
            {
                i = i++;
            }
            Console.WriteLine(i);
        }
    
    }
    }
    
    6 回复  |  直到 15 年前
        1
  •  7
  •   SLaks    15 年前

    i++ 是一个返回 i ,然后递增。

    因此, i = i++ 将评估 ,增量 ,然后分配 起初的 值,在它被递增之前。

    你需要使用 ++i ,它将返回递增的值。

        2
  •  7
  •   tvanfosson    15 年前

    我猜你真的想要一个解释为什么它不能按预期工作,而不是实际得到结果,因为你可以通过设置 i 首先等于200。

    创建变量的临时副本后应用postccrement运算符。临时的用于语句中的操作,然后执行赋值,因此循环等效于:

        for (int n = 0; n < 100; n++)
        {
            j = i;
            i++;
            i = j;
        }
    

    既然如此,增量基本上被丢弃了 从来没有增加过。

        3
  •  5
  •   Hank    15 年前
    i = i++;
    

    这将i设置为i的旧值,然后递增。我想你想要:

    i++;
    

    或者更好的是,如果您的编译器是跛脚的,并且没有优化返回:

    ++i;
    

    干杯。

        4
  •  4
  •   user180326user180326    15 年前

    线路 i = i++; 向变量i写入两次。先执行post increment,然后由赋值语句覆盖它。

    试试看 i++;

        5
  •  3
  •   Jimmy Collins luisr    15 年前

    只使用i++,而不是i=i++。

        6
  •  1
  •   Community Mohan Dere    9 年前

    我猜你认为你会得到的是,我会随着每个循环递增,但是你编码它的方式是,你把I的值赋给它本身,++操作发生在“之后”,所以I的值似乎不会递增。 检查 What is the difference between ++i and i++?