gpt4 book ai didi

c++ - 递归模式 (C++)

转载 作者:行者123 更新时间:2023-11-28 08:09:17 24 4
gpt4 key购买 nike

我怀疑这种模式与斐波那契有关,但我很难将其联系起来。

我必须只使用递归。

我认为代码有点像这样。

#include <iostream>
#include <conio.h>

using namespace std;

int pattern(int number)
{
if(number % 3 == 1)
{
cout << "--|^++" << endl;
return number - 1;
}
else
{
return pattern(number - 1);
}
}
int main()
{
int number,newNumber;
cout << "Please give the number to print" << endl;
cin >> number;
newNumber = number * 2;
pattern(newNumber);

getch();
}

在这个模式中我可以注意到在每个奇数中都有一个“--|^++”。

对于 2 和 6 有一个 << "-||^++"<< endl;

数字是 5

--|^++
-||^+++
--|^++
|||^^+++++
--|^++
-||^+++
|||||^^^++++++++

这已经占用了我一个下午的时间,我需要建议或一本书。

我需要这个模式或代码的解决方案,"% "和 "/"之间的区别,以及错误检查。

最佳答案

else 分支将永远不会被视为您的第二个 if 条件始终为真:

else if(condition == 2,6)

逗号是序列运算符,它将所有子表达式从左到右运行,它的值是最右边的子表达式。

实际上,该行大致相当于

condition == 2;
if (6)

如果值不为零,则 if 条件被视为 true,因此,它在这里始终为 true。

如果您的意图是测试 condition 是 2 还是 6,则必须明确:

else if (condition == 2 || condition == 6)

关于c++ - 递归模式 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9515555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com