Sieve of eratosthenes error
Sieve of eratosthenes error
我是个新手,正在努力学习C++。我正在阅读编程:使用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;
}
}
错误的原因是什么?
问题可能出现在这里:
for (int i = 0; i < list.size(); ++i){
if (list[i] == 1){
int c;
c = i;
while (c < list.size()){
c += i;
list[c] = 0; //problem is here. On the last loops c+=i is too big
}
}
}
原因是在最外层的for循环中,您最终会得到i == list.size() - 1
。现在,如果c > 1
,您将得到c + i > list.size()
,那么您将尝试访问list[c+i]
,这是一个大于素数的list
大小的索引。这就是为什么当你为1运行它时,它会工作,但对任何其他更大的数字都会失败。
至于编译器警告,那是因为size()
返回一个无符号的size_t
,而循环变量i
是一个有符号的int。当你比较它们时,这就是编译器所抱怨的。将循环更改为:
for (size_t i = 0; i < list.size(); ++i){
编译器的警告就会消失。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 使用 LuaBridge 将 LuaJIT 绑定到C++会导致"PANIC: unprotected error"
- OpenMP卸载说'fatal error: could not find accel/nvptx-none/mkoffload'
- C++错误:"error: int aaa::bbb is protected within this context"
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 使用 cmake 的 LLVM 构建在 tsan_libdispatch_mac.cc 期间失败; "Error: conflicting types for ..."
- C++ "error: invalid use of void expression"
- struct.error:解压缩 C++ 结构时,解包需要 288 字节的缓冲区
- 如何修复"error: ‘_1’ was not declared in this scope"?
- 从不同目录执行时"symbol lookup error:",否则从构建目录执行时按预期工作
- 对象声明中的模板"error: expected expression"
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- OpenCV 3.4.1 error readNetFromTensorflow 无法在 cv::d nn::ReadProtoFromBinaryFile 中打开 .pb
- 已解决 - C++ 的崇高文本中的"fatal error: opencv: no such file or directory"
- 为什么我会"error: expected expression"?
- CMake Error at modules/videoio/cmake/detect_ffmpeg.cmake:16
- 如果两个静态库使用相同的另一个静态库,如何避免"LNK2005 Already Defined error"?
- Sieve of eratosthenes error