gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:06:11 25 4
gpt4 key购买 nike

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com