警告:简单的家庭作业,不知道我在做什么
所以,我正在尝试制作一个程序,找到从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);
}
该程序没有捕获任何语法错误,但每次我尝试运行它时它也会冻结。知道为什么会这样吗?感谢。
答案 0 :(得分:9)
您使用:
for (number = 1; number < 100; number = number++)
虽然你应该写
for (number = 1; number < 100; number++)
您应该阅读这些文章,了解原始代码未增加的原因:for,++ Operator
您可以在某些测试代码中了解++
运算符的行为:
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