对于相同的输入参数,多个函数调用返回不同的结果
Multiple function calls return different results for same input arguments
#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;
相关文章:
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 返回指向对象的指针的函数调用是否为 prvalue?
- 如何在递归函数调用中返回当前函数值
- 了解在返回值之前和之后使用 EAX 的函数调用
- 为什么 c++11 std::normal_distribution 在从函数调用时返回相同的模式?
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- C ++ DLL导入:函数调用返回错误的结果
- 在C++中将结构从被调用函数返回到调用函数的适当方法是什么
- C++函数返回无法调用 SysFreeString() 的函数的 BSTR
- 使用布尔值稍后返回还是调用函数并立即返回更快?C++
- 为什么函数调用是xvalue(如果返回类型为rvalue)
- GCC 9.1 返回 void& 作为显式析构函数调用的结果类型。这是一个错误吗?
- 这些函数调用的返回指针的区别是什么?
- 为什么我不能在插入的函数调用中直接使用返回的指针作为参数
- 从指针返回对象时出现意外的析构函数调用
- 内置运算符(新的,删除和函数调用除外)如何返回
- 在C++11中按值返回构造的对象时,避免复制构造函数调用
- 动态分配(堆上)的对象的析构函数是否会在返回函数中自动调用
- 从函数返回时调用构造函数和析构函数的频率
- Rand() 在每次函数调用时返回相同的值