【问题标题】:Output giving multiple values of each number when they should be single values当每个数字应该是单个值时,输出给出多个值
【发布时间】: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。

标签: c# class output primes


【解决方案1】:

if (isPrime) 部分移出分解循环。 (如果你创建一个单独的bool isPrime(int n) 方法,这样的事情会更容易注意到。)

【讨论】:

    猜你喜欢
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 2017-11-12
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    相关资源
    最近更新 更多