我试图编写一个C ++程序,以通过使用Fibonacci系列检查是否是金色矩形(如果Fibonacci术语=长度,则前面的Fibonacci系列应该=宽度),这意味着它是金色矩形,而不是金色矩形。 。 我收到错误堆栈溢出.. !!!
这是我的代码:
#include "stdafx.h"
#include "iostream"
using namespace std;
int fib (int);
int _tmain(int argc, _TCHAR* argv[])
{
int length;
cout << "enter the Length " << endl;
cin>> length ;
int breadth;
cout << "enter the Breadth " << endl;
cin>> breadth ;
int x ;
cout << "enter the limit " << endl;
cin>> x ;
cout << endl ;
for (int i =1 ; i <= x ; i++ )
{
cout << "Fibonacci"<<"=" <<fib(i) <<" "<<"Counter =" << (i) << endl;
if ((breadth == (fib(i)-1)) && ( length == fib(i)))
{
cout << " rectangle";
}
else
{
cout << "This is not rectangle";
}
}
system ("pause");
return 0;
}
int fib (int n)
{
if (n == 1)
return 1;
if (n == 2)
return 2;
return fib (n - 1) + fib (n - 2);
}
答案 0 :(得分:1)
使用
return fib (n - 1) + fib (n - 2);
递归计算斐波那契数列不是正确的策略。这会导致很多不必要的重复计算和递归调用。
最好使用迭代方法。
int fib (int n)
{
int s1 = 0;
int s2 = 1;
for ( int iter = 1; iter <= n; ++iter )
{
int temp = s1;
s1 = s2;
s2 = temp + s1;
}
return s2;
}
如果必须使用递归方法,则需要一个帮助函数,以使递归的工作量减少。
int fib_helper(int s1, int s2, int iter, int n)
{
if ( iter == n )
{
return s2;
}
return fib_helper(s2, s1+s2, iter+1, n);
}
int fib (int n)
{
return fib_helper(0, 1, 1, n);
}
答案 1 :(得分:1)
您可以一次性完成所有操作。无需多次计算斐波那契数:
int lastFib = 1;
int currentFib = 1;
while(length >= currentFib)
{
//Check if the current pair of Fibonacci numbers matches the rectangle
if(length == currentFib && width == lastFib)
{
std::cout << "This is a golden rectangle" << std::endl;
return;
}
//Calculate the next Fibonacci number
int nextFib = lastFib + currentFib;
lastFib = currentFib;
currentFib = nextFib;
}
//We left the loop without returning, i.e., the rectangle is not golden.
std::cout << "This is not a golden rectangle" << std::endl;