不规则的间距书写呼吸道模式

发布于 2025-01-29 16:47:23 字数 608 浏览 3 评论 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;
}

我写了此代码以打印引导模式,但是我收到的输出具有不规则的间距,无论我在代码中找不到错误。

#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.

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谎言月老 2025-02-05 16:47:23

我假设“正确”的间距是 其中所有1的阵容 。您可以尝试以下一些步骤来解决问题:

1。 1的位置如何确定?
该位置应由最后一行确定,从n开始 - 因为根据您的程序,我们不需要前面的任何空间。

2。 1在哪个位置出现在最后一行?
在字符1之前,有空格和其他数字 - n-1 数字从n2,并且同样是相同数量的空间,因为每个字符之后都会显示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 from n to 2, 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 before 1.

3. Finally, How many spaces are required before line k?
For line k, we can use the above step to know that before the character 1 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文