对于相同的输入参数,多个函数调用返回不同的结果

Multiple function calls return different results for same input arguments

本文关键字:返回 函数调用 结果 于相同 输入 参数      更新时间:2023-10-16
#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从[第一个,最后一个]开始工作。这意味着它不包括last,因此很容易阅读整个集合。您不想使用point.end() + 1,因为这意味着它将尝试处理point.end()

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

将行更改为

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