使用abs()解决这个模式[我得到了我的输出..关闭]
PS我是一个初学者,我试图找到以下输出:
1
1 2 3
1 2 3 4 5
1 2 3 4 5 6 7
1 2 3 4 5
1 2 3
1
这是我的尝试:
#include<stdio.h>
#include<conio.h>
void main() {
int n;
scanf("%d",&n);
for(int i=1;(i<=2*n);i++){
int temp=1,t=2*n-1;
for(int j=0;j<abs(n-i);j++){
printf(" ");
}
for(int j=t;j>=abs((2*(i-1))-t);j--) {
printf(" %d",temp);
temp++;
}
printf("\n");
}
}
如你所见..我尽力删除 i=n 条件,但未成功。或者如果有人可以提供更简单的方法来打印图案..我将不胜感激
P.S. I'm a beginner and I was trying to find the following output :
1
1 2 3
1 2 3 4 5
1 2 3 4 5 6 7
1 2 3 4 5
1 2 3
1
and here's my try :
#include<stdio.h>
#include<conio.h>
void main() {
int n;
scanf("%d",&n);
for(int i=1;(i<=2*n);i++){
int temp=1,t=2*n-1;
for(int j=0;j<abs(n-i);j++){
printf(" ");
}
for(int j=t;j>=abs((2*(i-1))-t);j--) {
printf(" %d",temp);
temp++;
}
printf("\n");
}
}
as you can see.. I tried my best to remove the i=n condition UNSUCCESSFULLY. or if anyone can provide a more easier way to print the pattern.. I'd my grateful
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于给定的正输入
n
,您希望打印2 * n - 1
行。现在考虑每行的缩进:它从
n - 1
位置向下计数到 0,然后向上计数到n - 1
。如果您对从 1 开始的行进行编号,则该缩进为abs(n - line)
位置。每行打印的数字计数可以视为缩进的函数:最大值为 2 * n - 1,每个缩进单位都会将其减少 2。稍微重新排列一下,给出每行打印的最大值
2 * (n - indent) - 1
。对于您编写一个打印模式的程序来说,这些信息应该足够了,在所有模式行上使用单个外循环,并有意义地使用
abs()
函数。细节保留为应有的练习。For a given positive input
n
, you want to print2 * n - 1
lines.Now consider the indent of each line: it counts from
n - 1
positions down to 0, then back up ton - 1
. If you number the lines starting with 1, then that indent isabs(n - line)
positions.The count of numbers to print on each line can be viewed as a function of the indent: the maximum is
2 * n - 1
, and each unit of indent reduces that by 2. With a bit of rearrangement, that gives a maximum value to print on each line of2 * (n - indent) - 1
.That should be sufficient information for you to write a program that prints your pattern, using a single outer loop over all the pattern lines, and employing the
abs()
function meaningfully. The details are left as the exercise they are meant to be.