gpt4 book ai didi

c++ - 为什么这不会编译?三角函数

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

这个问题类似于斐波那契数列,只是我们将最后三个数字加在一起而不是最后两个数字。它被称为 Tribonacci。

INPUT:序列中 3 个起始数字的数组/列表,以及 (n) 您希望最终模式有多长,例如 30 个数字或仅 10 个数字等,

输出:一个 n 长的数组,包含开头的 3 个数字,并且是正确的 Tribonacci 模式。

我在 codewars 网站上这样做,所以错误代码有点不同。我在这里遇到麻烦的大部分原因是因为我对 vector 了解不多而且我无法计算。

std::vector<int> tribonacci(std::vector<int> signature, int n)
{
std::vector<int> result;

//add last 3 to get n

result[0]=signature[0];
result[1]=signature[1];
result[2]=signature[2];
std::cout << "Hello, World!" << std::endl;


for(int i = 3; i < n; i++) {
result[i] = signature[i-1] + signature[i-2] + signature[i-3];
std::cout << result[i];
}

return result;
}

我收到错误代码 139,但没有通过任何测试。

最佳答案

你不能在没有值的情况下访问 vector 的索引,因为它是未定义的行为。例如,您可能以 sigsegv 结尾。有几种处理方法,例如:

  1. 初始化具有 n 个值的 result vector ,而不是大小为 0 的 vector :
std::vector<int> result(n);
// + setting first 3 values from signature vector
  1. 使用 push_back 而不是索引:
auto result = signature;

然后在循环中:

int sum = result[i-1] + result[i-2] + result[i-3];
result.push_back(sum)

注意:此处使用result vector 而不是signature 来计算结果序列中的下一个元素。


顺便说一下,您可能对更通用的函数 x_bonacci 感兴趣:

假设我们有一个函数对给定 vector 的部分元素求和,例如:

int sum_subvector(std::vector<int>& vector, int start, int how_many){
int sum = 0;
auto start_it = vector.begin() + start;
auto end_it = start_it + how_many;
for(auto it = start_it; it != end_it; ++it)
sum += *it;
return sum;
}

我们可以有这样的x-bonacci函数:

// get n-element fibonacci sequence 
// where each element in the sequence consists of a sum of previous x elements
// signature - vector with first x elements of the sequence
std::vector<int> x_bonacci(std::vector<int> signature, int n){
int x = signature.size(); // for tribonacci x = 3

if(n < x){
return std::vector<int>(signature.begin(), signature.begin() + n);
}

auto result = signature;
for(int i = x; i < n; i++){
auto next_result = sum_subvector(result, i - x, x);
result.push_back(next_result);
}
return result;
}

只需稍加改动,您就可以将它变成 tribonacci

使用示例:

// get first 20 elements of the tribonacci sequence:
auto tribo20 = x_bonacci({0, 1, 2}, 20);
for(auto x: tribo20)
std::cout << x << ',';

关于c++ - 为什么这不会编译?三角函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56583190/

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