不规则的间距书写呼吸道模式
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
int space=n-i;
for(int j=1;j<=space;j++){
cout<<" ";
}
for(int k=i;k>=1;k--){
cout<<k<<" ";
}
for(int l=2;l<=i;l++){
cout<<l<<" ";
}
cout<<endl;
}
return 0;
}
我写了此代码以打印引导模式,但是我收到的输出具有不规则的间距,无论我在代码中找不到错误。
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
int space=n-i;
for(int j=1;j<=space;j++){
cout<<" ";
}
for(int k=i;k>=1;k--){
cout<<k<<" ";
}
for(int l=2;l<=i;l++){
cout<<l<<" ";
}
cout<<endl;
}
return 0;
}
I wrote this code for printing a palindrome pattern but the output I received has irregular spacing and no matter what I couldn't find the error in the code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设“正确”的间距是 其中所有
1
的阵容 。您可以尝试以下一些步骤来解决问题:1。
1
的位置如何确定?该位置应由最后一行确定,从
n
开始 - 因为根据您的程序,我们不需要前面的任何空间。2。
1
在哪个位置出现在最后一行?在字符
1
之前,有空格和其他数字 - n-1 数字从n
到2
,并且同样是相同数量的空间,因为每个字符之后都会显示1个空间,除了最后一个空间,在这里没关系。总共 2(n-1)字符1
。3。最后,在行
k
?之前需要多少个空间
对于行
k
,我们可以使用上面的步骤知道字符1
有 2(k-1)字符,但是我们需要 2(N-1)填充长度。因此,我们可以以 2(n-1)-2(k-1)= 2(nk)来获得线路前的所需空间。这就是为什么您需要在第7行上的“ Times 2”。尝试找到问题的步骤。
I assume the "correct" spacing is where all the
1
's line up. Here are some steps you could try to solve the problem:1. How is the position of
1
determined?The position should be determined by the last line, starting with
n
— since we don't require any spaces on the front, according to your program.2. At which position will
1
appear on the last line?Before the character
1
, there are spaces and other numbers — n-1 numbers fromn
to2
, and also the same number of spaces, since 1 space is presented after every character, except the last, which doesn't matter here. In total, 2(n-1) characters before1
.3. Finally, How many spaces are required before line
k
?For line
k
, we can use the above step to know that before the character1
there are 2(k-1) characters, but we need 2(n-1) to fill the length. Thus, we can obtain the required space in front of the line as 2(n-1)-2(k-1) = 2(n-k). That's why you need the "times 2" over there on line 7.Try to find steps toward problems.