大括号 - 递归
curly brackets - recursion
本文关键字:递归 更新时间:2023-10-16
我之前读过一些关于使用大括号的问题,据我了解,如果你只有一行,不使用大括号是可以的,但如果你要使用多行代码,你需要使用括号。
我有一个作业,老师确实要求我们在每种情况下都使用括号,以养成好习惯。他还允许我们研究和使用示例代码。
现在,我的问题是,我找到了一些不使用括号的示例代码。当我尝试将括号添加到代码中时,它会使我的输出不正确。有人可以向我解释如何在多行代码中正确使用大括号,并就如何实现我正在寻找的结果提出建议。
这是输出正确的代码:
void printStars(int i, int n)
// The calling program invokes this function as follows: printStars(1, n);
// n >= 1
{
if(i == n)
{
for(int j = 1; j <= n; j++) cout << '*'; cout << endl;
for(int j = 1; j <= n; j++) cout << '*'; cout << endl;
}
else
{
for(int j = 1; j <= i; j++) cout << '*'; cout << endl;
printStars(i+1, n); // recursive invocation
for(int j = 1; j <= i; j++) cout << '*'; cout << endl;
}
} // printStars
int main() {
int n;
int i=0;
cout << "Enter the number of lines in the grid: ";
cin>> n;
cout << endl;
printStars(i,n);
return 0;
}
当我尝试"清理它"时,如下所示:
void printStars(int i, int n)
// The calling program invokes this function as follows: printStars(1, n);
{
if(i == n)
{
for(int j = 1; j <= n; j++)
{
cout << '*';
cout << endl;
}
for(int j = 1; j <= n; j++)
{
cout << '*';
cout << endl;
}
}
else
{
for(int j = 1; j <= i; j++)
{
cout << '*';
cout << endl;
}
printStars(i+1, n); // recursive invocation
for(int j = 1; j <= i; j++)
{
cout << '*';
cout << endl;
}
}
} // printStars
int main() {
int n;
int i=0;
cout << "Enter the number of lines in the grid: ";
cin>> n;
cout << endl;
printStars(i,n);
return 0;
}
问题是你在打印循环中放了太多:
for(int j = 1; j <= i; j++)
{
cout << '*';
cout << endl;
}
应该是:
for(int j = 1; j <= i; j++)
{
cout << '*';
}
cout << endl;
不带大括号的循环只能包含一个语句。这意味着仅在循环结束时调用使用 cout
的行尾打印。
这是使用大括号的完整代码:
void printStars(int i, int n)
// The calling program invokes this function as follows: printStars(1, n);
// n >= 1
{
if(i == n)
{
for(int j = 1; j <= n; j++){
cout << '*';
}
cout << endl;
for(int j = 1; j <= n; j++){
cout << '*';
}
cout << endl;
}
else
{
for(int j = 1; j <= i; j++){
cout << '*';
}
cout << endl;
printStars(i+1, n); // recursive invocation
for(int j = 1; j <= i; j++){
cout << '*';
}
cout << endl;
}
} // printStars
int main() {
int n;
int i=0;
cout << "Enter the number of lines in the grid: ";
cin>> n;
cout << endl;
printStars(i,n);
return 0;
}
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 使用递归时获取变量的奇怪值
- 如何在C++中递归地按相反顺序打印集合
- 到连接组件算法的问题(递归)
- 如何使用递归打印修改后的星号三角形图案
- 使用递归模板动态分配的多维数组
- 递归函数有效,但无法记忆
- 包含模板文件的递归会导致编译失败