我想问是否有人可以帮助我完成一个函数。我想向我的函数提供一个输入(例如 4),该函数将生成以下数字:
1-222-33333-44444444
我不想只是打印它们,我想生成它们,这样我就可以将这些数字保存到表格中。
for(r=1; r<=num; r++)
{
for(sp=num-r; sp>0; sp--)
printf(" ");
for(c=1; c<=r; c++)
printf("%d", r);
for(k=2; k<=r; k++)
printf("%d", r);
printf("\n");
}
最佳答案
从问题中尚不完全清楚您想要实现的目标。假设您想要将 C 字符串生成为 "1-222-33333-44444444"
这里有一个解决方案:
#include <stdio.h>
#include <stdlib.h>
char *produce_char_sequence(int n);
int main(void)
{
char* str = produce_char_sequence(4);
printf("%s\n", str);
free(str);
return 0;
}
char *produce_char_sequence(int n)
{
int i, j, idx;
char *str = malloc(n * (n + 1)); // n**2 + n - 1 + 1
if (str == NULL) {
fprintf(stderr, "cannot allocate memory by malloc\n");
exit(EXIT_FAILURE);
}
idx = 0;
for (i = 1; i <= n; i++) {
for (j = 1; j <= 2*i - 1; j++)
str[idx++] = '0' + i;
if (i != n) // unless within last iteration
str[idx++] = '-';
}
str[idx] = '\0';
return str;
}
字符数来自1 + 3 + 5 + .. + 2n-1
arithmetic progression ,总计为 n2。然后,您还需要容纳 n-1 个 '-'
字符的空间和一个用于结束 空字符 的空间。
请注意,n
可能限制为 9
。请参阅 http://ideone.com/Gi7KxG 中的示例.
关于c - 需要有关 C 语言方法的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27219754/