程序得到一个“ n”,它将减去序列直到达到0,最后我们的输出是我们从“ n”中减去的序列的数量。这是一个示例:
我们可以说1 + 3 + 8 + 21 + 55进行输入88,并且按顺序排列它们是斐波那契序列中的序列1、3、5、7、9。在输出中,它们应显示为降序。
我的代码:
#include <iostream>
#include <vector>
using namespace std;
int getInput();
unsigned long long fibo(unsigned long long num, int& sum, vector<int>& b);
int main()
{
int n = getInput();
vector<int> bases;
int sum{ n };
fibo(n, sum, bases);
int s = bases.size();
for (int i{ s - 1 }; i >= 0; i--) {
if ((n - bases.at(i)) >= 0) {
n = n - bases.at(i);
cout << i + 1;
if (n != 0)
cout << " ";
}
}
cout << endl;
return 0;
}
//Functions
int getInput()
{
int x;
cin >> x;
return x;
}
unsigned long long fibo(unsigned long long num, int& sum, vector<int>& b)
{
int n = num;
if (n < 2)
return n;
int f1 = 0, f2 = 1, f3;
for (int i = 2; sum >= 0; i++) {
f3 = f1 + f2;
f1 = f2;
f2 = f3;
sum -= f3;
b.push_back(f3);
}
return f3;
}
我不知道我的代码有什么问题,但是在某些示例中它没有给我正确的答案。感谢您的帮助
答案 0 :(得分:0)
我很难遵循你的逻辑。我试图将其分解为我可以理解的部分。我想这经常发生。
我使用了一个fib生成向量,该向量可以创建从0,1,1,2等开始的所有fib值,直到传入的数字为止。
最后我只为诊断生成两次。如果我需要在两个地方使用它,我会改变它。但是,最初的问题并没有在最后要求其他诊断输出。
如果您有任何疑问,请告诉我。
#include <iostream>
#include <vector>
using namespace std;
using Fib_vector = std::vector<std::uint64_t>;
//Functions
// Get an integer input from the user
int getInput()
{
int x;
cout << "Please input a number for a final fibonacci sum: \n";
cin >> x;
return x;
}
// Create a map of fibonacci numbers up to a maximum value of max
int next_fib(Fib_vector &fib_vector)
{
return (fib_vector.rbegin()[0] + fib_vector.rbegin()[1]);
}
void fill_fib_vector(Fib_vector &fib_vector, int max)
{
fib_vector = {0, 1};
int next;
while ((next = next_fib(fib_vector)) < max)
fib_vector.push_back(next);
}
void fibo(uint64_t num, vector<int> &sequence_vector)
{
Fib_vector fib_vector;
// if (num < 2)
// return num; // I would probably just comment out this special case.
int remainder = num; // store the remaining portion from the subtrations in remainder
fill_fib_vector(fib_vector, num); // initialize our fib vector
for(int seq = fib_vector.size()-1; remainder > 0; seq--) {
if(fib_vector[seq] <= remainder) {
remainder -= fib_vector[seq];
sequence_vector.push_back(seq);
}
}
}
int main()
{
int n = getInput();
vector<int> sequence;
fibo(n, sequence);
for(auto element: sequence) {
// subtract 1 from the index because we used a fib vector with a 0 starting point
cout << (element - 1) << " ";
}
cout << endl;
// further dumping:
Fib_vector fib_vector;
fill_fib_vector(fib_vector, n);
int sum;
cout << endl;
for(auto element: sequence) {
cout << fib_vector[element] << " ";
sum += fib_vector[element];
}
cout << " : sum = " << sum;
return 0;
}