c++ - 多个函数调用对相同的输入参数返回不同的结果

标签 c++ function

#include <iostream>
#include <cmath>
#include <numeric>
#include <vector>
#include <algorithm>

bool isPointWithinSphere(std::vector<int> point, const double &radius) {

    std::transform(point.begin(), point.end(), point.begin(), [](auto &x)    {return std::pow(x,2);});

    return std::sqrt(std::accumulate(point.begin(), point.end() + 1, 0,     std::plus<int>())) <= radius;   
}


int countLatticePoints(std::vector<int> &point, const double &radius, const     int &dimension, int count = 0) {


     for(int i = -(static_cast<int>(std::floor(radius))); i <= static_cast<int>(std::floor(radius)); i++) {
        point.push_back(i);

        if(point.size() == dimension){
            if(isPointWithinSphere(point, radius)) count++;
        }else count = countLatticePoints(point, radius, dimension, count);

        point.pop_back();
    }

    return count;
}

主要

int main() {
std::vector<int> vec {};
std::cout << countLatticePoints(vec, 2.05, 2) << std::endl;
std::cout << countLatticePoints(vec, 1.5, 3) << std::endl;
std::cout << countLatticePoints(vec, 25.5, 1) << std::endl;
std::cout << countLatticePoints(vec, 2.05, 2) << std::endl;
}

以上程序运行返回如下结果:

13
19
51
 9

我试图理解为什么我的第一个函数调用使用相同的输入参数返回 13(正确答案)作为结果,但是当我稍后使用完全相同的输入参数再次调用该函数时,我得到 9作为答案?

想不出有什么理由会发生这种情况。

最佳答案

std::accumulate 从 [first, last) 开始工作。这意味着它不包括 last,因此很容易阅读整个集合。您不想使用 point.end() + 1,因为这意味着它将尝试处理 point.end()

这样做意味着您正在读取 vector 边界之外并导致未定义的行为。

将行改为

return std::sqrt(std::accumulate(point.begin(), point.end(), 0,     std::plus<int>())) <= radius;   

关于c++ - 多个函数调用对相同的输入参数返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37336344/

相关文章:

c++ - 类模板重载、类型名和类型名 vector

r - 使用 mlr-package 构建模型时的自定义性能测量

c - 不是将所有参数传递给函数不好吗?

c - 如何在 C 中的被调用函数中使用文件指针

c++ - 协助对 pthread_cond_wait() 的错误理解

c++ - 是否有任何不属于 C++ 标准库的 STL header ?

c++ - 如何在 Windows Server 2003 及更高版本上使用虚拟磁盘服务 (VDS) 登录 iSCSI 目标?

c++ - 未定义的行为或 gcc 优化错误

php - 需要为此函数进行适当的数组计算

python - 如何在 Python 中返回多个值?