c程序打印look and say序列
c program to print look and say sequence
这是我的代码实际输出和要求的输出略有不同。
在实际输出中,每个数字都在新行打印。
但我希望输出以 space.
分隔的单行打印
需要输出
示例输入:
1 8
示例输出:
1 11 21 1211 111221 312211 13112221 1113213211
我的代码在这里
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1,i=1,lim,s;
scanf("%d",&s);
scanf("%d",&lim);
for (sprintf(a, "%d",s); (b = realloc(b, len * 2 + 1)); a = b, b = x)
{
puts(x = a);
for (len = 0, cnt = 1; (c = *a); )
{
if (c == *++a)
cnt++;
else if (c)
{
len += sprintf(b + len, "%d%c", cnt, c);
cnt = 1;
}
}
if(i==lim)
break;
i++;
}
return 0;
}
我的输出
输入 > 1
8
输出>1
11
21
1211
111221
312211
13112221
1113213211
使用
printf("%s ",a);
而不是
puts(x = a);
puts automatically appends a newline. If that's not what you want, you can fputs your string to stdout or use printf.
fputs(x=a,stdout);
或
printf("%s ",a);
这是我的代码实际输出和要求的输出略有不同。 在实际输出中,每个数字都在新行打印。 但我希望输出以 space.
分隔的单行打印需要输出
示例输入:
1 8
示例输出:
1 11 21 1211 111221 312211 13112221 1113213211
我的代码在这里
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1,i=1,lim,s;
scanf("%d",&s);
scanf("%d",&lim);
for (sprintf(a, "%d",s); (b = realloc(b, len * 2 + 1)); a = b, b = x)
{
puts(x = a);
for (len = 0, cnt = 1; (c = *a); )
{
if (c == *++a)
cnt++;
else if (c)
{
len += sprintf(b + len, "%d%c", cnt, c);
cnt = 1;
}
}
if(i==lim)
break;
i++;
}
return 0;
}
我的输出
输入 > 1
8
输出>1
11
21
1211
111221
312211
13112221
1113213211
使用
printf("%s ",a);
而不是
puts(x = a);
puts automatically appends a newline. If that's not what you want, you can fputs your string to stdout or use printf.
fputs(x=a,stdout);
或
printf("%s ",a);