记录一道题,当时脑子抽了,规律愣是没找出来,做了俩个小时,感觉自己菜的不行,之后又做了一遍,也要30到40分钟才能做出来, 感觉自己水平还是有待提高。。。
这种题目主要就是找到规律,有点类似高中技术的VB题,不过这种找规律不熟练的话确实要找很久,还是题目做的太少了。。
期末考试前还是要再来做一遍这道题。。
**
Problem A: 数字菱形
**
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 4122 Solved: 2175
Description
观察例子,打印出如下图形
Input
多组测试数据,每组输入1个大于1小于9的整数,为菱形的边
Output
对于每组输出数字菱形
Sample Input
2
3
Sample Output
2
212
2
3
323
32123
323
3
代码如下
#include<stdio.h>
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i=1,m=1;
for(i;i<=2*n-1;i++) //打印
{
int count,j;
if(n>=i) //正三角空格的打印
{
count=n-i;
}
else //倒三角空格的打印
{
count=i-n;
}
for(j=1;j<=count;j++)
{
putchar(' ');
}
if(i<=n) //正三角数字的打印
{
int j,x=n,judge=0;
for(j=1;j<=2*i-1;j++)
{
if(x>=n-i+1&&judge==0) //前半段数字打印
{
char y=x+'0';
printf("%c",y);
x--;
}
else
{
if(x==n-i) //后半段数字打印
{
x++;
}
judge=1;
x++;
char y=x+'0';
printf("%c",y);
}
}
}
else //倒三角数字的打印
{
int j,x=n,judge=0;
m++;
for(j=1;j<=4*n-2*i-1;j++)
{
if(x>=m&&judge==0) //前半段数字打印
{
char y=x+'0';
printf("%c",y);
x--;
}
else //后半段数字打印
{
judge=1;
if(x==m-1)
{
x++;
}
x++;
char y=x+'0';
printf("%c",y);
}
}
}
putchar('\n');
}
}
}
其实我的代码还是比较low的,后三角的打印我懒的找规律了,就引入了m变量省略了找规律那一步。
之后我去网上找了其他人的代码学习了一下,确实让我瞠目结舌,真的很强,他们是精简到极致,找到了全部的规律,并且都用最简洁的形式表示了出来。
代码如下
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int n;
int i,j;
while (scanf("%d",&n)!=EOF){
//行控制
for(i=1;i<=2*n-1;i++){
//正三角形输出
if(i<=n){
for(j=1;j<=n-i;j++){
printf(" ");
}
for(j=1;j<=2*i-1;j++){
if(j<=i)
printf("%d",n-j+1);
else
printf("%d",n-i+j-i+1);
}
}
//倒三角形输出
else
{
for(j=1;j<=i-n;j++){
printf(" ");
}
for(j=1;j<=4*n-2*i-1;j++){
if(j<2*n-i)
printf("%d",n-j+1);
else
printf("%d",2*i-3*n+j+1);
}
}
printf("\n");
}
}
return 0;
}
大佬链接:https://blog.csdn.net/weixin_43272781/article/details/82851142