user1
当我将向量#include <algorithm>
#include <numeric>
#include <vector>
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(), 0,
std::plus<int>())) <= radius;
}
void print_container(std::vector<int> &vec) {
for (auto i : vec) std::cout << i << " ";
std::cout << std::endl;
}
void foo(std::vector<int> &vec, int k, int nest_level) {
for (int i = -k; i <= k; i++) {
vec.push_back(i);
if (vec.size() == nest_level) {
if (isPointWithinSphere(vec, k)) print_container(vec);
}
if (vec.size() != nest_level) foo(vec, k, nest_level);
vec.pop_back();
}
}
int main() {
std::vector<int> vec{};
std::vector<int> p{1, 0, 1};
std::cout << isPointWithinSphere(p, 1.5);
foo(vec, 1.5, 3);
}
传递给函数p {1, 0, 1}
时,结果为isPointWithinSphere(p, 1.5)
。现在,当我的函数true
生成向量foo
并将其传递给{ 1, 0, 1 }
时,它将返回isPointWithinSphere
。
为什么我的功能会为同一输入提供两个不同的答案?
答案 0 :(得分:4)
期待你截断你的号码。
std::cout << isPointWithinSphere(p, 1.5);
^^^ Double.
Calls =>
bool isPointWithinSphere(std::vector<int> point, const double &radius)
^^^^^^ Good.
BUT:
foo(vec, 1.5, 3);
^^^^ Double
Calls =>
void foo(std::vector<int> &vec, int k, int nest_level) {
^^^^^^ Ooops
在输入foo()
之前,k的值被截断为1。因此,当它稍后用于调用函数isPointWithinSphere()
时,它只会得到1。
正如@Jeremy Friesner在评论中指出的那样:
temp.cpp:36:12:警告:从'double'到'int'的隐式转换将值从1.5更改为1 [-Wliteral-conversion] foo(vec,1.5,3);
编译器实际上会告诉您这些类型的错误。您应该确保您的代码在最高警告级别上以零警告进行编译(这可以在所有现代编译器上完成)。
答案 1 :(得分:1)
在你的foo()函数中,参数k是一个整数,所以1.5将被转换为1.我确定这个转换是你的问题。但是,请自行帮忙,不要使用比较运算符在for循环中使用浮点值。