C语言实现【计算在2^4000内数字0到9的分布】代码+运行结果

目录:

            • 1.题目要求:
            • 2.C语言代码:
            • 3.运行结果:


1.题目要求:

编写任意精度整数运算包。要使用类似于多项式运算的方法。计算在2^4000内数字0到9的分布。


2.C语言代码:

ps: 学习于《数据结构与算法分析-C语言描述》

文件1:源文件

#include"list.h"

Position ListMulti(List L, List E, ElementType baseNum){	/*一次的乘法:列表头结点、尾结点、乘数*/
	ElementType carry = 0;	/*进位*/
	Position P = L->next;
	if (!P){
		fprintf(stderr, "ERROR:%s", "空链表");/*错误提示*/
		exit(1);
	}
	while (P || carry){
		if (P){
			P->num = P->num*baseNum + carry;
			carry = P->num / 10;
			P->num %= 10;
		}
		else{	/*else if (!P && carry)位数增加添加链表节点*/
			E = Insert(carry % 10, L, E);
			P = E;	/*不要忘记加,下面有p=p->next,必须满足有方的p存在*/
			carry /= 10;
		}
		P = P->next;
	}
	return E;	/*不要忘记返回哦*/
}

int* freqCount(List L){	/*数字频率统计*/
	int* a = (int*)malloc(10 * sizeof(int));
	int i;
	for (i = 0; i <= 9; i++){	/*初始化*/
		a[i] = 0;
	}
	Position p = L->next;
	while (p){	/*想用循环时不要用if,应该用while*/
		a[p->num]++;
		p = p->next;
	}
	return a;
}
int main(){
	List HeadNode = CreateNode();	/*创建链表*/
	Position EndNode = HeadNode;	/*结尾节点or插入结点*/
	EndNode = Insert(1, HeadNode, EndNode);	/*第一个节点*/
	ElementType baseNum;	/*底数*/
	ElementType powerNum;	/*指数*/
	printf("请输入底数:\n");
	scanf("%hd", &baseNum);
	printf("请输入指数:\n");
	scanf("%hd", &powerNum);

	int i;	/*进行幂次运算*/
	for (i = 1; i <= powerNum; i++){
		EndNode = ListMulti(HeadNode, EndNode, baseNum);
	}

	ListInversion(HeadNode);	/*链表反转*/

	printf("\n%hd的%hd次幂是:\n",baseNum,powerNum);
	PrintfList(HeadNode);
	printf("\n");

	int* a = NULL;
	a = freqCount(HeadNode);
	for (i = 0; i <= 9; i++){
		printf("%d的次数是%d\n", i, a[i]);
	}
	return 0;
}

文件2:list.h

#ifndef _LIST_H

#include
#include

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
typedef short int ElementType;

Position CreateNode();
Position Insert(ElementType num, List L, Position P);
void ListInversion(List L);
void PrintfList(List headNode);

#endif	/*_LIST_H*/

struct Node{
	ElementType num;
	Position next;
};

Position CreateNode(){	/*返回创建节点指针*/
	Position P = (Position)malloc(sizeof(struct Node));
	if (!P){
		fprintf(stderr, "ERROR:%s", "out of space");/*错误提示*/
		exit(1);
	}
	P->next = NULL;
	return P;
}

Position Insert(ElementType num, List L, Position P){	/*返回插入数据节点的指针*/
	if (!P){
		fprintf(stderr, "ERROR:%s", "插入结点不存在");/*错误提示*/
		exit(1);
	}
	Position NewP = CreateNode();
	NewP->num = num;
	NewP->next = P->next;
	P->next = NewP;
	return NewP;
}

void ListInversion(List L){
	Position froNode, midNode, aftNode;
	froNode = L->next;
	midNode = froNode->next;
	froNode->next = NULL;
	while (midNode){
		aftNode = midNode->next;
		midNode->next = froNode;
		froNode = midNode;
		midNode = aftNode;
	}
	L->next = froNode;
}

void PrintfList(List headNode){
	Position p = headNode->next;
	while (p){
		printf("%hd", p->num);
		p = p->next;
	}
}



3.运行结果:

C语言实现【计算在2^4000内数字0到9的分布】代码+运行结果_第1张图片

你可能感兴趣的:(C语言实现【计算在2^4000内数字0到9的分布】代码+运行结果)