Hello,
I am writing a program for an exercise homework and for some reason my Boolean function is not doing any of the calculations.
This was the question: At McDonald's, you can purchase 6, 9 and 20 packs of McNuggets. Call a number of McNuggets buyable if it is possible to buy that number of McNuggets. Write a recursive boolean method called
buyable(int n) that returns true if n is buyable.
e.g. buyable(15) is true, buyable(11) is false.
ret is always equal to zero, I am not sure how to make it work.
#include <iostream>
usingnamespace std;
bool buyable(int n) // calculate the sum of n+(n-1)+(n-2) + … + 2+1
{
bool ret = false;
if (n<1)
{
returnfalse;
}
if((n%6)==0 || (n%9)==0 ||(n%20)==0)
{
returntrue;
cout<<"n: "<<n;
}
if (ret == false && n > 20 || n > 9 || n > 6)
{
ret = buyable(n - 20);
cout<<"n: "<<n<<endl;
cout<<"ret: "<<ret;
}
return ret;
}
int main()
{
//cout<<"Enter the number of McNuggets you would like to purchase. ";
buyable(15);
if (buyable(11)==true)
{
cout<<"You can buy "<<buyable(11)<<" McNuggets!"<<endl;
}
if (buyable(11)==false)
{
cout<<"You can not buy "<<"n"<<" McNuggets!"<<endl;
}
//cout<<buyable(15);
return 0;
}
Line 18: The && operator has higher priority than ||, thus the expression is evaluated as:
if ( (ret == false && n > 20) || n > 9 || n > 6)
Probably not what you wanted.
I suspect you wanted:
if (ret == false && (n > 20 || n > 9 || n > 6)) // Note the parens
However, ret==false is irrelevant. It is initialized to false and not changed between lines 7 and 18, therefore there is no need to test that it is false.