我有一个游戏,游戏的重点是在21圈内找到解决方案。如果找不到解决方案,则应输出"无解决方案",并继续在主机中继续。如果有解决方案,则应该将其上下堆叠并输出每个步骤(目前向后很好(。
当我找不到解决方案时,我正在尝试弄清楚如何在不打印任何东西的情况下离开堆栈。目前,它将打印" 21圈中没有解决方案"。但是,然后仍然上堆栈,打印一举一动。有解决方案时,它确实可以。
bool TabletStock(int _tablets, int _turns) {
if (_tablets == 18){
cout << "Found solution. I have exactly 18 tablets, with " << 21 - _turns << " moves left.n";
return 1;
}
_turns++;
if (_turns >= 21){
cout << "No solution in 21 turns.n";
return 0;
}
if (_tablets % 2 == 1){
TabletStock((++_tablets) / 2, _turns);
cout << "After incrementing, reduce " << _tablets << " by half to get " << _tablets / 2 << ".n";
}
else if (_tablets % 3 == 0 && _tablets % 18 == 0){
TabletStock(_tablets / 3, _turns);
cout << "With " << _tablets << ", divide by 3 to get " << _tablets / 3 << ".n";
}
else{
TabletStock((_tablets + 24), _turns);
cout << "With " << _tablets << ", add 24 to get " << _tablets + 24 << ".n";
}
}
目前的功能调用是tabletstock(int,0(;
我一直在尝试在" if(_turns> = 21("语句中做一些事情,因为它在打印所有步骤之前打印了所有步骤,因此,如果我找到了一种从该if语句,也许我可以得到它不输出所有的cout步骤。
调用tablestock((时,它将返回bool。每个印刷品都应用if语句包装。如果是错误的,请不要打印。
例如,更改以下内容:
TabletStock((_tablets + 24), _turns);
cout << "With " << _tablets << ", add 24 to get " << _tablets + 24 << ".n";
to:
if(TabletStock((_tablets + 24), _turns))
{
cout << "With " << _tablets << ", add 24 to get " << _tablets + 24 << ".n";
}
您可以将字符串存储在范围之外的变量中,或将其添加到函数paramater中,每次将结果附加到字符串变量中。
if (_tablets % 3 == 0 && _tablets % 18 == 0)
{
mystring += "After incrementing, reduce ....... ";
TabletStock(_tablets / 3, _turns);
}
,如果最后:
if (_tablets == 18)
{
cout << mystring << endl;
return 1;
}