当我调试这个程序时,我看到max是一个垃圾号,而不是我传递给它的值。
#include <iostream>
#include <cmath>
float findPrimes(int max) {
float* primes = new float[max];
bool* boolarray = new bool[max];
for(int i=0; i<=max; i++) {
boolarray[i] = true;
}
int x = 1;
for(int i=2; i<=sqrt(max); i++) {
if(boolarray[i]) {
for(int j=pow(i, 2)+x*i; j<=max; x++)
{
boolarray[j] = false;
}
}
}
int n = 0;
while(n<=max) {
if(boolarray[n])
primes[n] = boolarray[n];
n++;
}
return primes[max];
}
int main() {
float answer = findPrimes(6);
printf("%f\n", answer);
_sleep(10000);
return 0;
}它告诉我,max是一个垃圾数字,当我调试它,所以这就是为什么程序不执行(它运行,但什么都没有发生)。我很肯定我做了所有的数学正确(使用埃拉托斯提尼的筛子),那么是什么呢?
编辑:
#include <iostream>
#include <cmath>
float findPrimes(int max) {
std::cout << max << "\n";
float* primes = new float[max-1];
bool* boolarray = new bool[max-1];
for(int i=0; i<=max-1; i++) {
boolarray[i] = true;
}
int x = 1;
for(int i=2; i<=sqrt(max); i++) {
if(boolarray[i]) {
for(int j=pow(i, 2)+x*i; j<=max-1; x++)
{
boolarray[j] = false;
}
}
}
int n = 0;
while(n<=max-1) {
if(boolarray[n])
primes[n] = boolarray[n];
n++;
}
return primes[max-2];
}
int main() {
printf("%f\n", findPrimes(6));
_sleep(10000);
return 0;
}发布于 2013-03-03 01:15:53
你越界了。
bool* boolarray = new bool[max-1];
for(int i=0; i<=max-1; i++) {
boolarray[i] = true;
}假设最大值为5,第一行分配数字为0到3的4个bools,循环从0到4,但没有条目4。只有4个条目,0、1、2和3。
你应该这么做:
bool* boolarray = new bool[max];
for(int i=0; i<max; i++) {
boolarray[i] = true;
}现在,如果最大值为5,则分配5个bools,编号为0到4。您的循环现在从0到4,这就是您想要的。
https://stackoverflow.com/questions/15181224
复制相似问题