【发布时间】:2021-12-12 07:23:49
【问题描述】:
我的任务是计算一个数字的阶乘,保存到一个结构中然后打印出来。
结构体代码如下:
struct fact_entry
{ /* Definition of each table entry */
int n;
long long int lli_fact; /* 64-bit integer */
char *str_fact;
};
之后是下一个代码。我已经定义了一个 long long int 变量来计算阶乘,并且将这个数字首先保存到结构的元素中没有问题,打印功能可以正常工作。问题在于 char *str_fact;变量,我编写了一个代码来使用 sprintf 将 int 值更改为 char,但是在我将此值分配给结构后,在下一个 for 循环中它只打印计算的最后一个元素。如果我尝试在第一个循环内打印它,一切正常,但在外面它只打印最后一个。
int
main (int argc, char *argv[])
{
int n;
int i;
struct fact_entry *fact_table;
if (argc != 2)
panic ("wrong parameters");
n = atoi (argv[1]);
if (n < 0)
panic ("n too small");
if (n > LIMIT)
panic ("n too big");
/* Your code starts here */
// Allocate memory
// Compute fact(n) for i=0 to n
fact_table = calloc(n+1, sizeof(struct fact_entry));
long long int f=1;
char buf[20];
for (i = 0; i <= n; i++)
{
if (i == 0) {
f = f * i + 1;;
}
else{
f=f*i;
}
sprintf(buf, "%lld", f);
printf("%s\n", buf);
fact_table[i].n = i;
fact_table[i].lli_fact = f;
fact_table[i].str_fact = buf;
}
/* Your code ends here */
// print computed numbers
for (i = 0; i <= n; i++)
{
printf ("%d %lld %s\n", fact_table[i].n, fact_table[i].lli_fact, fact_table[i].str_fact);
}
/* Your code starts here */
// Free memory
free(fact_table);
/* Your code ends here */
return 0;
}
如何将 buf 变量写入结构。我只能更改/*your code */之间的代码
【问题讨论】:
标签: c pointers char structure factorial