为什么 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;
}
最佳答案
您的基本错误是您没有在每次 while
迭代后将变量 y
重置为零。它只能增长,当测试数字3时,它已经足够大,不能让任何数字通过,因此它只通过数字2。
快速修复:之后
if (y < 3)
{
cout << a << ", " << endl;
x = x - 1;
}
a = a + 1;
插入
y = 0;
另一个错误是您只检查小于 11 的数字,这意味着例如 121 (11*11) 将是误报,您的程序会认为它是质数,而实际上它不是。
也就是说,您应该学习如何编写更易于自己调试的代码,尤其是使用调试器。如果您从未使用过调试器,请不要担心,您会很容易找到相关教程。在您的情况下,调试器会向您显示 y 的状态,并且您会看到它达到了它不应该达到的数字。
future 代码的两个一般提示:
使用描述性变量名。 x 和 y 对我来说听起来像坐标,但它们不是。给它们适当的名称,例如
number_dividers
而不是 y。将您的代码分成几部分。例如,有这样一个函数:
#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++;
}
}
(描述性的变量名让第一次看代码的人更容易理解,你同意吗?)
关于c++ - 显示 N 个素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53387790/