For my assignment, I need to create a io interface routine for the tribonacci equation but it keeps causing the program to stop working and completely fails. Any idea why this is happening? Only the tribonacci is failing. The quad seems to be fine...
#include <iostream>>
#include <cmath>
usingnamespace std;
void printMenu (int &option)
{
cout << "please enter the number corresponding to choice\n\n";
cout << "1) compute the time for one complete swing of a pendulum.\n\n";
cout << "2) compute the double real roots of a quadratic equation.\n\n";
cout << "3) compute the nth number of the tribonacci sequence.\n\n";
cout << "4) quit.\n\n\n";
cout << "option = ";
cin >> option;
}
int quadratic (int a, int b, int c, float &r1, float &r2)
{
float discrim;
discrim = (b*b)-(4*a*c);
if ((a==0)||(discrim < 0))
return -1;
else
{
r1= (-b - sqrt(discrim))/(2*a);
r2= (-b + sqrt(discrim))/(2*a);
return +1;
}
}
void quadIO ()
{
float r1,r2;
int a,b,c;
do
{
cout << "Enter 3 coefficients for the quadratic equation.\n";
cout << "a= ";
cin >> a;
cout << "b = ";
cin >> b;
cout << "c= ";
cin >> c;
if (quadratic(a,b,c,r1,r2)==-1)
cout << "error: the quadratic must have 2 real roots\n\n";
else
cout << "the roots are " << r1 << " and " << r2 <<endl;
}
while ((a==0)||(b*b-(4*a*c)<0));
}
unsignedlong tribonacci (int n)
{
if (n==0) return 0;
if (n==1) return 1;
return tribonacci(n-1)+tribonacci(n-2)+tribonacci(n-3);
}
void tribonacciIO ()
{
int n;
cout << "Enter an integer between 1 and 38 to computer the nth tribonacci number\n";
do
{
cout << "n= ";
cin >> n;
if ((n<0) || (n>38))
cout << "n must be >=0 and <=38.\n";
}
while ((n<0) || (n>38));
cout << "The " << n << "th " << "tribonacci number is " << tribonacci(n) <<endl;
}
void quit ()
{
cout << "you have chosen to quit.";
}
int main ()
{
int option;
while (option!=5)
{
printMenu (option);
switch (option)
{
case 2: quadIO (); break;
case 3: tribonacciIO (); break;
case 4: quit (); break;
default: cout << " there is no option for " << option << ". please choose another option"<<endl;
}
}
}
I said n=2. That is clearly between 0 and 38. tribonacciIO calls tribonacci(2). What have we there?
1 2
// n == 2
return tribonacci(n-1)+tribonacci(n-2)+tribonacci(n-3);
In other words: return tribonacci(1)+tribonacci(0)+tribonacci(-1); // To -inf and beyond
Remember that even the tribonacci(38) will call tribonacci(2) many times.