c++ - 将该值传递给函数时值会发生变化吗?

标签 c++ math

当我调试这个程序时,我看到 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;
}

最佳答案

您访问范围外。

bool* boolarray = new bool[max-1];
for(int i=0; i<=max-1; i++) {
    boolarray[i] = true;
}

假设max是5,第一行分配了4个bool,编号从0到3。循环从0循环到4。但是没有entry 4。只有4个entry,0,1,2,3 .

你可能应该这样做:

bool* boolarray = new bool[max];
for(int i=0; i<max; i++) {
    boolarray[i] = true;
}

现在,如果最大值为 5,您将分配 5 个 bool 值,编号为 0 到 4。您的循环现在从 0 到 4,这就是您想要的。

关于c++ - 将该值传递给函数时值会发生变化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15181224/

相关文章:

c++ - 无法为 Qt 5.5 配置编译器和构建工具包

javascript - 使用 Math.PI 降低曲线速度

php - 一个数字占另一个数字的百分比

math - 由角度分隔的轴

c# - 为什么 Math.Round 不返回 int?

c++ - 派生类的内联函数能否覆盖基类的非内联函数?

c++ - 在 C++ 项目中留下未使用的类有什么缺点?

c++ - 多次使用 Promise

algorithm - 汽车停在无限的街道上 : find car and compute the complexity

C++ 和 R 接口(interface),获取输出