【发布时间】:2014-01-15 02:44:10
【问题描述】:
我是新手,我正在努力学习 C++。我正在阅读Programming: Principles and Practice Using C++,在第 4 章中,有一个练习可以让程序使用 Eratosthenes 的筛子找到素数,但是我的程序不起作用,我不确定为什么。
当我尝试编译它时,我收到以下警告:
警告 C4018:“
然后当我运行它时,它会崩溃并出现以下调试错误:
R6010 -abort() 已被调用
看了半天代码,没找到错误。我是新手,所以我不知道signed 和unsigned 的确切含义,但我尝试了x 的各种输入,例如10、100、1000。
调试器显示:
“ConsoleApplication1.exe 中 0x759B2EEC 处未处理的异常:Microsoft C++ 异常:内存位置 0x0031F8C4 处的 Range_error。”
这是我的代码:
#include "../../std_lib_facilities.h"
int main()
{
//program to find all prime numbers up to number input
vector<int> list(2,0); //to skip 0 and 1
int x;
cout << "Find all primes up to: ";
cin >> x;
for (int i = 0; i < (x-1); ++i){
list.push_back(1); //grow the vector and assigns 1
}
for (int i = 0; i < list.size(); ++i){
if (list[i] == 1){ //find the next prime
int c;
c = i;
while (c < list.size()){
c += i; //then finds all its multiples and,
list[c] = 0; //assign 0 to show they can't be primes
}
}
}
for (int i = 0; i < list.size(); ++i){ //goes through the vector
if (list[i] == 1) //write only primes
cout << i << endl;
}
}
错误的原因是什么?
【问题讨论】:
-
有关有符号/无符号不匹配的警告可能来自您执行 i
-
你要求它找到最大的质数?
-
你的调试器说什么?
-
我将 int 更改为 unsigned int 并且消息消失了,但对于除 1 之外的任何数字,我仍然收到调试错误。
标签: c++ algorithm sieve-of-eratosthenes