【发布时间】:2013-11-21 11:25:56
【问题描述】:
我正在学习 C 和 C#。这个问题是针对 C# 的。我正在阅读的书中的这段代码给出了错误的输出。书中的图片只给出了每个数字的一个实例的输出,但我的代码给出了每个数字输出的多个实例。我的电脑有问题吗?
这是课程代码:
namespace practice_6
{
public class Primes
{
private long min;
private long max;
public Primes()
: this(2, 100)
{
}
public Primes(long minimum, long maximum)
{
if (min < 2)
min = 2;
else
min = minimum;
max = maximum;
}
public IEnumerator GetEnumerator()
{
for (long possiblePrime = min; possiblePrime <= max; possiblePrime++)
{
bool isPrime = true;
for (long possibleFactor = 2; possibleFactor <= (long)Math.Floor(Math.Sqrt(possiblePrime)); possibleFactor++)
{
long remainderAfterDivision = possiblePrime % possibleFactor;
if (remainderAfterDivision == 0)
{
isPrime = false;
break;
}
if (isPrime)
{
yield return possiblePrime;
}
}
}
}
}
}
这是来自 main 的代码:
static void Main(string[] args)
{
Primes primesFrom2To1000 = new Primes(2, 1000);
foreach (long i in primesFrom2To1000)
Console.Write("{0} ", i);
Console.ReadKey();
这是输出:
【问题讨论】:
-
它不仅给出多个值,还给出非质数,如 975 和 999。