[英]Program in c to print flloyd's triangle . Program stops working
我在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
等等
您可以先构造字符串(较大的字符串),然后在每行中仅打印一部分:
#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;
}
启用警告编译,你很快就会看到你需要打印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:在您发布的代码中:连接字符串时,您弄乱了参数的顺序。
这应该为您提供所需的输出:
#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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.