我试着编写一个打印带有镜像字母的钻石的程序,如下面的形状:
a
aba
abcba
abcdcba
abcdedcba
abcdefedcba
abcdedcba
abcdcba
abcba
aba
a
这是我已经做过的事情:
#include <stdio.h>
int main()
{
int n, c, k,f=0, space = 1;
char ch='a';
printf("enter the size of diamond\n");
scanf("%d", &n);
space = n - 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space--;
for (c = 1; c <= 2*k-1; c++)
if (c <= f)
printf("%c", ch);
ch++;
if (c>f)
ch--;
printf("%c", ch);
printf("\n");
}
space = 1;
for (k = 1; k <= n - 1; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space++;
for (c = 1 ; c <= 2*(n-k)-1; c++)
printf("a");
printf("\n");
}
return 0;
}
但显然这段代码中有一些错误,任何人都可以帮我检测一下吗?
答案 0 :(得分:0)
int n, c, k, space;
printf("enter the size of diamond\n");
scanf("%d", &n);
char s[n+2];
s[0] = 'a';s[1] = '\0';
for(c = 0; c < n; ++c){
space = n - c -1;
printf("%*s", space, "");
k = printf("%s", s) - 1;
while(--k >=0)
putchar(s[k]);
puts("");
s[c+1] = s[c] + 1;
s[c+2] = '\0';
}
for(c = 1; c < n; ++c){
space = c;
printf("%*s", space, "");
k = printf("%.*s", n - c, s) - 1;
while(--k >=0)
putchar(s[k]);
puts("");
}
#include <stdio.h>
void print(char from, char to){
putchar(from);
if(from < to){
print(from+1, to);
putchar(from);
}
}
int main(void){
int c = 0, n, k = 1;
printf("enter the size of diamond\n");
scanf("%d", &n);
do{
printf("%*s", n - c -1, "");
print('a', 'a' + c);
puts("");
if(c + 1 == n)
k = -k;
c += k;
}while(c>=0);
return 0;
}
答案 1 :(得分:0)
如果替换此
for (c = 1 ; c <= 2*(n-k)-1; c++)
printf("a");
用这个
for (c = 0 ; c < 2*(n-k)-1; c++) // note the different conditions
printf("%c", 'a' + c); // print char instead of string
你应该得到正确长度的每一行,但增加的字符如
abcde
但它并没有从中点减少。我把它留给你了!
答案 2 :(得分:0)
将任务分开运行会更容易。因此,根据位置和线长计算要打印的字符的功能是:
int getCharAtPos(int pos, int len)
{
if (pos > len / 2)
{
return 'a' + len - pos;
}
else
{
return 'a' + pos - 1;
}
}
然后使用
而不是printf("a")
for (c = 1; c <= 2*k-1; c++)
printf("%c", getCharAtPos(c, 2*k-1));
.....
for (c = 1 ; c <= 2*(n-k)-1; c++)
printf("%c", getCharAtPos(c, 2*(n-k)-1));
答案 3 :(得分:0)
问题的第二个解决方案。 你可以使用递归。 我为你的任务写了一个例子。
//--------------
// Recursive Out one Simbol
void DamSimRec(char chOut ,int scnt)
{
printf("%c", chOut);
if (scnt > 1)
{
DamSimRec(chOut + 1, scnt - 1);
printf("%c", chOut);
}
}// Print Space
//--------------
void SpaceOut(int pSizeSpace)
{
int a_c;
for (a_c = 0; a_c < pSizeSpace; a_c++)
printf(" ");
}
//--------------
// Recursive Print One String Krylov E.A.
void DamRec(int space, int sout)
{
SpaceOut(space);//space;
DamSimRec('a', sout);//Simbols
printf("\n");
if (space > 0)
DamRec(space-1, sout+1);
if (sout > 1)
SpaceOut(space + 1);
DamSimRec('a', sout - 1);
}
printf("\n");
}
main()
{
int aSize;
printf("enter the size of diamond\n");
scanf_s("%d", &aSize);
DamRec(aSize , 1);
}
...所以,你可以使用它,但要记住堆栈。