我对如何从用户输入中创建倒三角形感到困惑,因此每次都删除最后一个字符,并在每行的开头添加一个空格。所以这就是我现在所拥有的,应该正确减去空格(无论出于什么原因我似乎都无法使用它)。应该是一个非常简单的for循环,但是我无法一生解决这个问题。
现在运行时的样子如下:
Enter a string: EXAMPLE
E X A M P L E
E X A M P L
E X A M P
E X A M
E X A
E X
E
以及我想要的样子:
Enter a string: EXAMPLE
E X A M P L E
E X A M P L
E X A M P
E X A M
E X A
E X
E
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
char string[100];
int c, k, length;
printf("Enter a string: ");
gets(string);
length = strlen(string);
printf("\n");
for(c=length; c>0; c--)
{
for(k=0; k<c; k++)
{
printf("%c ", string[k]);
}
printf("\n");
}
getch();
}
最佳答案
您只需在打印每行之前添加length - c
空格,因为必须打印的字符越少,插入的空格就越多:
#include <stdio.h>
#include <string.h>
int main()
{
char string[100];
int c, k, length;
printf("Enter a string: ");
gets(string);
length = strlen(string);
printf("\n");
for(c=length; c>0; c--)
{
//Add some spaces
for(k=0; k < length - c ; k++)
{
printf(" ");
}
for(k=0; k<c; k++)
{
printf("%c ", string[k]);
}
printf("\n");
}
return 0;
}
SAMPLE STRING
的示例:Enter a string: SAMPLE STRING
S A M P L E S T R I N G
S A M P L E S T R I N
S A M P L E S T R I
S A M P L E S T R
S A M P L E S T
S A M P L E S
S A M P L E
S A M P L E
S A M P L
S A M P
S A M
S A
S