用了不少硬编码但很容易更改。我们知道:
下面的代码稍作修改便可以计算阶乘。
由斯特林公式
可得阶乘结果的位数:
如此便可得到相应的结构体大小。
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define N 10
int A[N];
typedef struct Node
{
int data;
struct Node *pNext;
}Node,*pNode;
void CreateNode(pNode *phead,int Size)
{
if (*phead == NULL)
{
pNode NewNode = (pNode)malloc(sizeof(pNode));
NewNode->data = 1;
NewNode->pNext = NULL;
*phead = NewNode;
}
pNode p = *phead;
for (int i = 2; i <=Size; i++)
{
pNode NewNode = (pNode)malloc(sizeof(pNode));
p->pNext = NewNode;
NewNode->data = 0;
NewNode->pNext = NULL;
p = NewNode;
}
}
void PrintAllNode(pNode phead)
{
memset(A, 0, sizeof(A));
if (phead == NULL)
{
printf("空链表\n");
return;
}
else
{
int i = 0;
pNode p = phead;
while (p!= NULL)
{
i++;
printf("%d", p->data);
A[p->data]++;
if (i % 3 == 0)
printf(",");
if (i % 50 == 0)
printf("\n");
p = p->pNext;
}
}
}
// 逆转链表函数
void RevList(pNode *phead)
{
pNode p, p1, p2;
p =*phead;
p1=p2 = NULL;
if (*phead == NULL)
{
return;
}
else
{
p1 = p->pNext;
while (p1!= NULL)
{
p2 = p1->pNext;
p1->pNext = p;
p = p1;
p1 = p2;
}
(*phead)->pNext = NULL;
(*phead) = p;
}
}
void Caculate(pNode phead,int n)
{
int k;
for (int i = 1; i <= n; i++)
{
int temp = 0;
for (pNode p = phead; p != NULL;p=p->pNext)
{
k = (p->data) * 2 + temp;
temp = k / 10;
p->data = k % 10;
}
}
}
int main()
{
int T = (int)(4000* log10(2)) + 1;
pNode head = NULL;
CreateNode(&head,T);
Caculate(head,4000);
RevList(&head);
PrintAllNode(head);
for (int i = 0; i < N; i++)
printf("\n%d出现%d次,其出现的频率为%.3f\n",i, A[i],(double)A[i]/T);
printf("\n");
system("pause");
return 0;
}