4

警告:简单的家庭作业,不知道我在做什么

所以,我正在尝试制作一个程序来查找从 1 到 100 的第一个素数并将它们打印在列表框中。这是我的代码:

private bool IsPrime(int number)
{
    int count;
    if (number == 2)
        return true;
    for (count = 3; count < number; count = count + 2)
    {
        if (number % count == 0)
            return false;
    }
    return true;
}

private void calculateButton_Click(object sender, EventArgs e)
{
    int number;
    for (number = 1; number < 100; number = number++)
        if (IsPrime(number))
            primeList.Items.Add(number);
}

并且该程序没有捕获任何语法错误,但每次我尝试运行它时它也会冻结。知道为什么会这样吗?谢谢。

4

1 回答 1

9

你用:

for (number = 1; number < 100; number = number++)

而你应该写

 for (number = 1; number < 100; number++)

您应该阅读这些文章以了解为什么您的原始代码没有增加 : for , ++ 运算符

您可以++在一些测试代码中了解操作员的行为:

        int n = 0;
        Console.WriteLine(n); //0
        n = n++;
        Console.WriteLine(n); //0
        n = ++n;
        Console.WriteLine(n); //1 
        n = n++;
        Console.WriteLine(n); //1
        n = ++n;
        Console.WriteLine(n); //2

另一个很好的例子是:

        int n = 0;
        int x = n++;
        int y = ++n;
        Console.WriteLine(string.Format("x={0}", x)); //0
        Console.WriteLine(string.Format("y={0}", y)); //2
        Console.WriteLine(x + y); //n++ + ++n == 0 + 2 == 2
        n = 0;
        x = ++n;
        y = n++;
        Console.WriteLine(string.Format("x={0}", x)); //1
        Console.WriteLine(string.Format("y={0}", y)); //1
        Console.WriteLine(x + y); //++n + n++ == 1 + 1 == 2
于 2012-10-05T00:13:57.387 回答