显示 N 个素数

Displaying N numbers of prime numbers

为什么 while 循环中的 for 循环只运行一次?另外,请告诉我我寻找素数的逻辑是否正确。该代码仅显示 2 作为输出。

#include <iostream>
using namespace std;

int main()
{
    int x, z = 0;
    int y = 0;
    int a = 2;

    cout << "Input the number of prime numbers you need: ";
    cin >> x;
    while (x > 0)
    {
        for (int i = 1; i < 11; i++) 
        {
            z = a % i;
            if (z == 0)
            {
              y = y + 1; 
            }
        }

        if (y < 3)
        {
            cout << a << ", " << endl;
            x = x - 1;
        }
        a = a + 1;
    }

    return 0;
}

这将解决问题。

 #include <iostream>
 using namespace std;

int main()
{
    int x, z = 0;
    int a = 2;

    cout << "Input the number of prime numbers you need: ";
    cin >> x; 
    while (x > 0) 
    {
        bool isPrime = true;
        for (int i = 2; i < a; i++) 
        {
            z = a % i;
            if (z == 0)
            {
                isPrime = false;
            }
        }

        if (isPrime)
        {
            cout << a << ", " << endl;
            x = x - 1;
        }

        a = a + 1; 
    } 
    return 0;
}

您的基本错误是您没有在 while 的每次迭代后将变量 y 重置为零。它只能增长,当测试数字3时,它已经足够大,不能让任何数字通过,因此它只通过数字2。

快速修复:在

之后
    if (y < 3)
    {
        cout << a << ", " << endl;
        x = x - 1;
    }
    a = a + 1; 

插入

    y = 0;

另一个错误是你只检查小于 11 的数字,这意味着例如 121 (11*11) 将是一个误报,你的程序会认为它是质数,而实际上它不是。

也就是说,您应该学习如何编写更易于自己调试的代码,尤其是使用调试器。如果您从未使用过调试器,请不要担心,您会很容易找到相关教程。在您的情况下,调试器会向您显示 y 的状态,您会看到它达到了它不应该达到的数字。

未来代码的两个一般提示:

  1. 使用描述性变量名。 x 和 y 对我来说听起来像坐标,但它们不是。给他们适当的名字,例如 number_dividers 而不是 y。

  2. 将您的代码分成几部分。例如,有这样一个函数:

    #include <cmath>
    
    bool is_prime(int number)
    {
        if(i <= 1) return false;
    
        for(int i = 2; i <= std::sqrt(number); i++)
        {
            if(number % i == 0) return false;
        }
        return true;
    }
    

拥有这样的函数可以使您的代码更整洁,允许您重用部分代码,并且,尤其是在您的情况下,允许您单独测试该代码单元,即测试是否针对给定的输入有正确的输出(本质上是单元测试)。

您的代码现在是:

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

//(insert code from above here)

int main()
{
    int required_primes = 0;
    cout << "State the amount of prime numbers to be found: ";
    cin >> required_primes;

    int found_primes = 0;
    int current_number = 2;
    while(found_primes < required_primes)
    {
        if(is_prime(current_number))
        {
            cout << "Found prime: " << current_number << endl;
            found_primes++;
        }
        current_number++;
    }
}

(描述性的变量名让第一次看代码的人更容易理解,你同意吗?)