我在c中写了下面的代码来打印floyd的三角形。
int main()
{
printf("Enter the number of rows you want to have");
int t;
scanf("%d",&t);
int i;
char a[1000] ="";
for(i=1;i<=t;i++)
{
if (i%2!=0)
{
strcat("1",a);
printf("%c\n",a);}
else
strcat("0",a);
printf("%c\n",a);
}
return 0;
}
程序对我来说似乎不错,但是一旦我执行它就会停止工作。请帮忙
我希望输出如下 -
1
01
101个
0101
10101个
等等
答案 0 :(得分:3)
您可以先构造字符串(较大的字符串),然后在每行中只打印一部分字符串:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Enter the number of rows you want to have");
int t;
scanf("%d",&t); // You should check the return value...
puts("");
char pattern[t + 1]; // It's a VLA, so you need a C99 compliant compiler or
// use your big array...
// Initialize the string (it's the last row) starting from the last
// char (the null terminator) and stepping back to first. Every row should
// end with a '1', so in the loop, start with it.
int i = t;
pattern[i] = '\0';
while ( i > 0 )
{
pattern[--i] = '1';
if ( i == 0 )
break;
pattern[--i] = '0';
}
// Print only the part needed in each row
char* tmp = &pattern[t - 1];
for ( int i = 0; i < t; ++i, --tmp )
{
printf("%s\n", tmp);
}
return 0;
}
答案 1 :(得分:2)
编译并启用警告,您很快就会发现需要使用a
(字符串格式)而不是%s
(字符格式)打印%c
。当我编译你的代码时,我得到了:
prog.c: In function 'main':
prog.c:16:22: warning: format '%c' expects argument of type 'int', but argument 2 has type 'char *' [-Wformat=]
printf("%c\n",a);
~^ ~
%s
prog.c:20:22: warning: format '%c' expects argument of type 'int', but argument 2 has type 'char *' [-Wformat=]
printf("%c\n",a);
~^ ~
%s
此外,您的else
语句缺少大括号,只会假定strcat()
为其正文。
要获得所需的输出,您应该放弃strcat()
并索引要分配位的位置,如下所示:
#include <stdio.h>
#include <string.h>
int main()
{
printf("Enter the number of rows you want to have\n");
int t;
scanf("%d",&t);
int i;
char a[1000] ="";
for(i=1;i<=t;i++)
{
if (i%2!=0)
{
a[999 - i] = '1';
printf("%s\n", &a[999 - i]);
}
else {
a[999 - i] = '0';
printf("%s\n", &a[999 - i]);
}
}
return 0;
}
输出:
Enter the number of rows you want to have
4
1
01
101
0101
请注意,999
是数组的大小,减去1。
PS:在你发布的代码中:当连接字符串时,你搞砸了参数的顺序。
答案 2 :(得分:2)
这可以为您提供您正在寻找的输出:
#include <iostream>
#include <string.h>
int main()
{
printf("Enter the number of rows you want to have: ");
int t;
scanf("%d", &t);
for (int i = 1; i <= t; i++)
{
for (int j = 1; j <= i; j++)
{
char a[1000] = "";
if ((i+j) % 2 == 0)
strcat(a, "1");
else
strcat(a, "0");
printf("%s", a);
}
printf("\n");
}
return 0;
}
由于每个其他行都以0开头,因此您只需在每行重新创建字符串a
。