在c++中搜索数组中的素数
C++ Array in a prime number search
所以我试图回答欧拉项目上的一个问题(问题是:找到10,001质数),并遇到了一个问题,我不知道为什么会发生这种情况。当我运行下面的c++代码时,
#include <iostream>
using namespace std;
int main()
{
int arr[10001]={2}, term=1, i, num=3;
while(term!=10001)
{
for(i=0; i<term; i++)
{
if(num%arr[i]==0){
break;
}
}
if(i==term){
arr[term]=num;
cout<< arr[term]<< " is prime"<< endl;
term++;
}
num++;
}
cout<< arr[term]<< endl;
}
我总是让cout<< arr[term]<< endl;
打印出任何n++;
(在本例中是下一个数字,但如果我将其更改为n=856
,则它将打印出该数字)。我不明白为什么数组项会改变,因为我认为它只会在arr[term]=num;
执行时改变
你的代码有未定义行为,因为你正在访问数组的边界之外。
当循环中断时,term
的值为10001
,这是数组arr
的第10002个元素,而您的数组内存只分配给10001
元素。
打印数组的最后一个元素,执行:
cout<< arr[term - 1]<< endl;
在每次迭代中,执行
arr[term]=num;
cout<< arr[term]<< " is prime"<< endl;
term++;
所以当while
结束时,term
是你上次赋值时使用的另一个
您必须输出arr[term-1]
而不是arr[term]
,因为term
在对arr[]
赋值结束时递增,因此term
变量比10001
多1。
编辑代码:
#include <iostream>
using namespace std;
int main()
{
int arr[10002]={2}, term=1, i, num=3;
while(term!=10001)
{
for(i=0; i<term; i++)
{
if(num%arr[i]==0){
break;
}
}
if(i==term){
arr[term]=num;
cout<< arr[term]<< " is prime"<< endl;
term++;
}
num++;
}
cout<< arr[term-1]<< endl;
//Your 'term' variable actually is term + 1, hence, you have
//to print the element at 'term - 1'.
}
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 在C++中搜索嵌套多映射值
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 为什么二进制搜索在我的测试中不起作用
- 正在尝试重载二进制搜索树分配运算符
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 向量上的线性搜索
- 如何在动态数组上使用搜索函数
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- cmake:添加要搜索头文件的目录
- 使用C++创建特殊的二叉搜索树
- 在C++的字符串中搜索和删除某些字符
- std::unordered_map 搜索算法是如何实现的?
- 使用不变量来确定二分搜索中的边界条件
- 二叉搜索如何比线性搜索更快?
- 按边长度递归搜索图中所有可行路径
- QStackWidget - 按名称搜索
- 在递归二叉搜索树中搜索
- 我的二进制搜索程序只是关闭了