查找素数的程序意外停止
A program to find prime numbers stops unexpectedly
我写了一个非常简单的程序来查找用户指定的某个范围内的素数。但是我遇到了一个问题。程序只是在达到合数时停止打印出素数。我试图了解为什么它会停止,但我根本不明白它有什么问题,可能是因为我是编程新手。无论如何,这是代码。
#include <iostream>
using namespace std;
int main()
{
int y;
int range;
cout << "Please enter the range. n";
cin >> range;
for (y = 2; y <= range; y++)
{
int result;
for (int x = 1; x < y - 1; x++)
{
int prime = y - x;
if (y%prime != 0)
{
}
else
{
result = 0;
}
}
if (result != 0)
{
cout << y << " is a prime number. n";
}
}
}
正如Brian Gradin指出的那样,我看到的唯一问题是你应该将结果初始化为非零整数。
int result = 1;
只有在此初始化之后,才能在 for 循环后进行有效检查,检查结果是否已更改为零。
如果不进行初始化,对此变量值的任何访问都会导致未定义的行为。
编辑:
为了完整起见,我应该添加其他人的建议,即更标准的方法将是:
for (y = 2; y <= range; y++)
{
bool isPrime = true;
// The following loop should be changed to loop through the Sieve of primes
for (int x = 2; x*x < y ; x++) // You need to loop only till sqrt(y)
{
if (y%x == 0) // if you found a factor
{
isPrime = false;
break;
}
}
if ( isPrime )
{
cout << y << " is a prime number. n";
// and add this to the sieve of primes.
}
}
int main()
{
int y;
int range;
int result;
int prime;
cout << "Please enter the range. n";
cin >> range;
for (y = 2; y <= range; y++)
{
result=1;
for (int x = 1; x <= y - 1; x++)
{
prime = y - x;
if (y%prime != 0)
{
}
else
{
result = 0;
}
}
if (result != 0)
{
cout << y << " is a prime number. n";
}
}
}
我已经更改了您的 forloops 限制语句..!!
for (int x = 1; x <= y - 1; x++)
并将您的声明更改为顶部:
int result=0;
int prime;
相关文章:
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 多线程程序中出现意外的内存泄漏
- C++ 程序意外退出
- 在gcc中意外调用了Const重载.编译器错误或兼容性修复程序
- 如果我删除指针,我的C++程序会意外删除系统文件吗?
- Qt 应用程序具有意外的 QDir::currentPath
- 排序程序的意外错误代码
- 以下程序的意外输出
- QT应用程序意外的语言事件
- 简单程序中的意外推力错误
- 程序意外终止C
- 设置终止和意外处理程序
- 双精度数字程序意外值
- QWT示例该程序已经意外完成
- 使用双精度的程序的意外行为
- 查找素数的程序意外停止
- 程序意外地完成了-QT创建者
- cpp 程序中的意外输出
- 当我在递归函数中调用 return 时,我的程序意外完成
- Arduino上的意外程序停止