( •̀ ω •́ )y( •̀ ω •́ )y精心整理C两百例【60例-120例】,持续更新.....

前言

汉诺塔问题、哈夫曼编码、图的深度优先遍历、八皇后问题、骑士巡游、绘制余弦曲线和直线的迭加、计算高次方数的尾数、打鱼还是晒网、怎样存钱以获取最大利息、阿姆斯特朗数、亲密数、自守数…

( •̀ ω •́ )y( •̀ ω •́ )y精心整理C两百例【1-60例】,持续更新…

61、二叉树遍历

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

typedef struct bitnode
{
	char data;
	struct bitnode *lchild, *rchild;
}bitnode, *bitree;

/** 创建二叉树 */
void createbitree(bitnode ** t, int *n)
{
	char x;
	bitnode *q;

	*n = *n + 1;
	printf("Input  %d  DATA: ", *n);
	x = getchar();
	if (x != '\n') getchar();

	if (x == '^')
		return;
	/* 创建根节点 */
	q = (bitnode*)malloc(sizeof(bitnode));
	q->data = x;
	q->lchild = NULL;
	q->rchild = NULL;
	*t = q;

	printf("This Address is:%o,Data is:%c, Left Pointer is:%o,Right Pointer is:  %o\n", q, q->data, q->lchild, q->rchild);

	createbitree(&q->lchild, n);	// 创建左子树
	createbitree(&q->rchild, n);	// 创建右子树
	return;
}

/** 打印 */
void visit(bitnode *e)
{
	printf("Address:  %o,  Data:  %c,  Left Pointer:  %o,  Right Pointer:  %o\n", e, e->data, e->lchild, e->rchild);
}

/** 前序遍历 */
void preordertraverse(bitnode *t)
{
	if (t)
	{
		visit(t);
		preordertraverse(t->lchild);
		preordertraverse(t->rchild);
		return;
	}
	return;
}

/** 计算二叉树叶子数 */
void countleaf(bitnode *t, int *c)
{
	if (t != NULL)
	{
		if (t->lchild == NULL && t->rchild == NULL)
			*c = *c + 1;

		countleaf(t->lchild, c);
		countleaf(t->rchild, c);
	}
	return;
}

/** 二叉树高度 */
int tree_high(bitnode *t)
{
	int lh, rh, h;
	if (t == NULL)
		h = 0;
	else
	{
		lh = tree_high(t->lchild);
		rh = tree_high(t->rchild);
		h = (lh > rh ? lh : rh) + 1;
	}

	return h;
}

void main()
{
	bitnode *t; int count = 0;
	int n = 0;
	printf("Please initialize the TREE!");
	createbitree(&t, &n);

	printf("This is TREE Struct:");
	preordertraverse(t);

	countleaf(t, &count);
	printf("This TREE has %d leaves.", count);

	printf("High of The TREE is: %d\n", tree_high(t));
	system("pause");
}

62、数字金额转为大写金额


#include<stdlib.h>
#include<string.h>
#include<stdio.h>


char c_je[51] = {0};  /* 大写金额字符变量 */

/** 数字金额转换为大写金额子程序 */
char* conversion(double x)                     
{
	int i = 0, n = 0, bz = 1;
	char money[14];        /* 数字金额的字符变量 */
	char temp[13];

	char f1[10][3] = { "零", "壹", "贰", "叁", "肆", "伍",
		"陆", "柒", "捌", "玖" };			 /*数字对应的大写数组变量*/

	char f2[11][3] = { "亿", "仟", "佰", "拾", "万",
		"仟", "佰", "拾", "元", "角", "分" }; /*每位数字对应单位数组变量*/
	sprintf(money, "%.01f", 100 * x);		 /* 转换成字符,精确到分 */
	n = strlen(money);
	for (i = 0; i < n; i++)
	{
		strcpy(temp, &money[i]);  /* 复制到临时数组 */

		if (atoi(temp) == 0)      /* 判断第i位后是否全为0 */
		{
			bz = 2;
			break;
		}
		if (money[i] != '0')
		{
			if (bz == 0)
				strcat(c_je, f1[0]);
			strcat(c_je, f1[money[i] - '0']); /* 数字串转化字符串 */
			bz = 1;
			strcat(c_je, f2[13 - n + i]);	/* 单位转换 */
		}
		else
		{
			if (n - i == 7 && (money[i - 1] != '0' || money[i - 2] != '0' || money[i - 3] != '0')) /* 判断万位位置 */
				strcat(c_je, "万");
			if (n - i == 3)					/* 判断个位数的元位置 */
				strcat(c_je, "元");
			bz = 0;
		}
	}
	if (bz == 2)
	{
		if (n - i >= 7 && n - i < 10)
			strcat(c_je, "万"); /* 万位数字为0,加‘万’ */
		if (n - i >= 3)
			strcat(c_je, "元");
		strcat(c_je, "正");		/* 最后不是分位,加“正” */
	}
	return c_je;				/* 返回大写金额 */
}

void main()
{
	double count;
	printf("*********************************************************\n");
	printf("*                                                       *\n");
	printf("*           数字金额转换为大写金额程序 Ver.1.0          *\n");
	printf("*                                                       *\n");
	printf("*                                                       *\n");
	printf("*               请输入要转换的金额:                    *\n");
	printf("*                     ");
	scanf("%lf", &count);
	printf("*           您输入的金额为:%10.2lf 。               *\n", count);
	printf("*                                                       *\n");
	printf("*转换为大写金额是:%s\n", conversion(count));
	printf("*                                                       *\n");
	system("pause");
}

63、汉诺塔问题

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

/* 实现将n个盘子从a移动到c */
void hanoil(int n, char a, char b, char c)
{
	if (n == 1)			/* 递归调用的出口,n=1 */
		printf("  >>  Move Plate No.%d from Stick %c to Stick %c.\n", n, a, c);
	else
	{
		hanoil(n - 1, a, c, b);  /* 递归调用 */
		printf("  >>  Move Plate No.%d from Stick %c to Stick %c.\n", n, a, c);
		hanoil(n - 1, b, a, c);
	}
}


void main()
{
	int n;
	char a = 'A';
	char b = 'B';
	char c = 'C';
	printf("This is a hanoil program.\nPlease input number of the plates:");
	scanf("%d", &n);
	if (n <= 0)
	{
		puts("n must no less than 1!");
		exit(1);
	}
	puts("The steps of moving plates are:");
	hanoil(n, a, b, c);
	system("pause");
}

64、哈夫曼编码


#include<stdlib.h>
#include<string.h>
#include<stdio.h>

#define MAX  1000
#define MAXSYMBS 30
#define MAXNODE 59

typedef struct
{
	int weight;
	int flag;
	int parent;
	int lchild;
	int rchild;
}huffnode;

typedef struct
{
	int bits[MAXSYMBS];
	int start;
}huffcode;

void main()
{
	huffnode huff_node[MAXNODE];
	huffcode huff_code[MAXSYMBS], cd;
	int i, j, m1, m2, x1, x2, n, c, p;

	/* 数组huff_node初始化 */
	printf("please input the leaf num of tree:");
	scanf("%d", &n);
	for (i = 0; i<2 * n - 1; i++)
	{
		huff_node[i].weight = 0;
		huff_node[i].parent = 0;
		huff_node[i].flag = 0;
		huff_node[i].lchild = -1;
		huff_node[i].rchild = -1;
	}

	printf("please input the weight of every leaf:");
	for (i = 0; i<n; i++)
		scanf("%d", &huff_node[i].weight);

	/* 构造哈夫曼树 */
	for (i = 0; i<n - 1; i++)
	{
		m1 = m2 = MAX;
		x1 = x2 = 0;
		for (j = 0; j<n + i; j++)
		{
			if (huff_node[j].weight<m1&&huff_node[j].flag == 0)
			{
				m2 = m1;
				x2 = x1;
				m1 = huff_node[j].weight;
				x1 = j;
			}
			else if (huff_node[j].weight<m2&&huff_node[j].flag == 0)
			{
				m2 = huff_node[j].weight;
				x2 = j;
			}
		}

		huff_node[x1].parent = n + i;    /*将找出的两棵子树合并为一棵子树*/
		huff_node[x2].parent = n + i;
		huff_node[x1].flag = 1;
		huff_node[x2].flag = 1;
		huff_node[n + i].weight = huff_node[x1].weight + huff_node[x2].weight;
		huff_node[n + i].lchild = x1;
		huff_node[n + i].rchild = x2;
	}

	/* 求字符的哈夫曼编码 */
	for (i = 0; i<n; i++)
	{
		cd.start = n;
		c = i;
		p = huff_node[c].parent;
		while (p != 0)
		{
			if (huff_node[p].lchild == c)

				cd.bits[cd.start] = 0;
			else
				cd.bits[cd.start] = 1;
			cd.start = cd.start - 1;
			c = p;
			p = huff_node[p].parent;
		}
		cd.start++;
		for (j = cd.start; j <= n; j++)
			huff_code[i].bits[j] = cd.bits[j];
		huff_code[i].start = cd.start;
	}

	/* 输出字符的哈夫曼编码 */
	puts("The Hafman code are:");
	for (i = 0; i<n; i++)
	{
		for (j = huff_code[i].start; j <= n; j++)
			printf("%10d", huff_code[i].bits[j]);
		printf("\n");
	}
	system("pause");
}

65、图的深度优先遍历

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

struct node                       /* 图顶点结构定义 */
{
	int vertex;                    /* 顶点数据信息 */
	struct node *nextnode;         /* 指下一顶点的指标 */
};

typedef struct node *graph;       /* 图形的结构新型态 */
struct node head[9];              /* 图形顶点数组 */
int visited[9];                   /* 遍历标记数组 */



/** 根据已有的信息建立邻接表 */
void creategraph(int node[20][2], int num)
{	/* num指的是图的边数 */
	graph newnode;								/* 指向新节点的指针定义 */
	graph ptr;
	int start;									/* 边的起点 */
	int end;									/* 边的终点 */
	int i;

	/* 读取边线信息,插入邻接表*/
	for (i = 0; i < num; i++)		
	{
		start = node[i][0];         /* 边线的起点 */
		end = node[i][1];           /* 边线的终点 */

		/* 建立新顶点 */
		newnode = (graph)malloc(sizeof(struct node));
		newnode->vertex = end;       /* 建立顶点内容 */
		newnode->nextnode = NULL;    /* 设定指标初值 */
		ptr = &(head[start]);        /* 顶点位置 */

		/* 遍历至链表尾 */
		while (ptr->nextnode != NULL)
			ptr = ptr->nextnode;     /* 下一个顶点 */
		ptr->nextnode = newnode;     /* 插入节点 */
	}
}


/** 图的深度优先搜寻法 */
void dfs(int current)
{
	graph ptr;

	visited[current] = 1;					/* 记录已遍历过 */
	printf("vertex[%d]\n", current);		/* 输出遍历顶点值 */
	ptr = head[current].nextnode;			/* 顶点位置 */
	while (ptr != NULL)						/* 遍历至链表尾 */
	{
		if (visited[ptr->vertex] == 0)		/* 如过没遍历过 */
			dfs(ptr->vertex);				/* 递回遍历呼叫 */
		ptr = ptr->nextnode;				/* 下一个顶点 */
	}
}


void main()
{
	graph ptr;
	int node[20][2] = { { 1, 2 }, { 2, 1 },  /* 边线数组 */
	{ 1, 3 }, { 3, 1 },
	{ 1, 4 }, { 4, 1 },
	{ 2, 5 }, { 5, 2 },
	{ 2, 6 }, { 6, 2 },
	{ 3, 7 }, { 7, 3 },
	{ 4, 7 }, { 4, 4 },
	{ 5, 8 }, { 8, 5 },
	{ 6, 7 }, { 7, 6 },
	{ 7, 8 }, { 8, 7 } };

	int i;
	/* 顶点数组初始化 */
	for (i = 1; i <= 8; i++)					
	{
		head[i].vertex = i;						/* 设定顶点值 */
		head[i].nextnode = NULL;				/* 指针为空 */
		visited[i] = 0;							/* 设定遍历初始标志 */
	}

	/* 建立邻接表 */
	creategraph(node, 20);						
	printf("Content of the gragh's ADlist is:\n");
	for (i = 1; i <= 8; i++)
	{
		printf("vertex%d ->", head[i].vertex);  /* 顶点值 */
		ptr = head[i].nextnode;					/* 顶点位置 */
		while (ptr != NULL)						/* 遍历至链表尾 */
		{
			printf(" %d ", ptr->vertex);		/* 印出顶点内容 */
			ptr = ptr->nextnode;				/* 下一个顶点 */
		}
		printf("\n");              
	}

	/* 打印输出遍历过程 */
	printf("The end of the dfs are:\n");
	dfs(1);                      
	printf("\n");                  
	system("pause");
}

66、图的广度优先遍历

#include <stdlib.h>
#include <stdio.h>
#define MAXQUEUE 10               /* 队列的最大容量 */

/* 图的顶点结构定义 */
struct node                       
{
	int vertex;
	struct node *nextnode;
};

typedef struct node *graph;       /* 图的结构指针 */
struct node head[9];              /* 图的顶点数组 */
int visited[9];                   /* 遍历标记数组 */

int queue[MAXQUEUE];              /* 定义序列数组 */
int front = -1;                   /* 序列前端 */
int rear = -1;                    /* 序列后端 */


/** 二维数组向邻接表的转化 */
void creategraph(int node[20][2], int num)
{
	graph newnode;					/* 顶点指针 */
	graph ptr;

	int start;                      /* 边起点 */
	int end;                        /* 边终点 */
	int i;

	for (i = 0; i < num; i++)		/* 第i条边的信息处理 */
	{
		start = node[i][0];         /* 边的起点 */
		end = node[i][1];           /* 边的终点 */

		/* 建立新顶点 */
		newnode = (graph)malloc(sizeof(struct node));
		newnode->vertex = end;			/* 顶点内容 */
		newnode->nextnode = NULL;		/* 设定指针初值 */
		ptr = &(head[start]);			/* 顶点位置 */

		/* 遍历至链表尾 */
		while (ptr->nextnode != NULL)	
			ptr = ptr->nextnode;        /* 下一个顶点 */
		ptr->nextnode = newnode;        /* 插入第i个节点的链表尾部 */
	}
}


/** 数值入队列 */
int enqueue(int value)
{
	if (rear >= MAXQUEUE)			/* 检查伫列是否全满 */
		return -1;                  /* 无法存入 */
	rear++;                         /* 后端指标往前移 */
	queue[rear] = value;            /* 存入伫列 */
}


/** 数值出队列 */
int dequeue()
{
	if (front == rear)				/* 队列是否为空 */
		return -1;                  /* 为空,无法取出 */
	front++;						/* 前端指标往前移 */
	return queue[front];			/* 从队列中取出信息 */
}


/** 图形的广度优先遍历 */
void bfs(int current)
{
	graph ptr;

	/* 处理第一个顶点 */
	enqueue(current);						/* 将顶点存入队列 */
	visited[current] = 1;					/* 已遍历过记录标志置疑1 */
	printf(" Vertex[%d]\n", current);		/* 打印输出遍历顶点值 */
	while (front != rear)					/* 队列是否为空 */
	{
		current = dequeue();				/* 将顶点从队列列取出 */
		ptr = head[current].nextnode;		/* 顶点位置 */
		while (ptr != NULL)					/* 遍历至链表尾 */
		{
			if (visited[ptr->vertex] == 0)	/* 顶点没有遍历过 */
			{
				enqueue(ptr->vertex);		/* 奖定点放入队列 */
				visited[ptr->vertex] = 1;	/* 置遍历标记为1 */

				printf(" Vertex[%d]\n", ptr->vertex);/* 印出遍历顶点值 */
			}
			ptr = ptr->nextnode;     /* 下一个顶点 */
		}
	}
}


void main()
{
	graph ptr;
	int node[20][2] = { { 1, 2 }, { 2, 1 },  /* 边信息数组 */
	{ 6, 3 }, { 3, 6 },
	{ 2, 4 }, { 4, 2 },
	{ 1, 5 }, { 5, 1 },
	{ 3, 7 }, { 7, 3 },
	{ 1, 7 }, { 7, 1 },
	{ 4, 8 }, { 8, 4 },
	{ 5, 8 }, { 8, 5 },
	{ 2, 8 }, { 8, 2 },
	{ 7, 8 }, { 8, 7 } };
	int i;
	puts("This is an example of Width Preferred Traverse of Gragh.\n");
	/* 顶点结构数组初始化 */
	for (i = 1; i <= 8; i++)        
	{
		head[i].vertex = i;
		head[i].nextnode = NULL;
		visited[i] = 0;
	}
	/* 图信息转换,邻接表的建立 */
	creategraph(node, 20);       
	printf("The content of the graph's allist is:\n");
	for (i = 1; i <= 8; i++)
	{
		printf(" vertex%d =>", head[i].vertex); /* 顶点值 */
		ptr = head[i].nextnode;					/* 顶点位置 */
		while (ptr != NULL)						/* 遍历至链表尾 */
		{
			printf(" %d ", ptr->vertex);		/* 打印输出顶点内容     */
			ptr = ptr->nextnode;				/* 下一个顶点 */
		}
		printf("\n");               
	}
	printf("The contents of BFS are:\n");
	bfs(1);										/* 打印输出遍历过程 */
	printf("\n");                 
	system("pause");
}

67、求解最优交通路径

#include <stdlib.h>
#include <stdio.h>

/** 定义边的类型 */
typedef struct ArcCell{
	int adj;  /*相邻接的城市序号*/
}ArcCell; 

/** 定义顶点的类型 */
typedef struct VertexType{
	int number;		/*城市序号*/
	char *city;		/*城市名称*/
}VertexType; 

/** 定义图的类型 */
typedef struct{
	VertexType vex[25];   /* 图中的顶点,即为城市 */
	ArcCell arcs[25][25]; /* 图中的边,即为城市间的距离 */
	int vexnum, arcnum;   /* 顶点数,边数 */
}MGraph; 

MGraph G; /* 把图定义为全局变量 */

int P[25][25] = { 0 };	// 城市之间是否可到达
long int D[25] = { 0 };	// 存储距离

/** 造图函数 */
void CreateUDN(int v, int a)
{ 
	int i, j;
	G.vexnum = v;		// 25个城市
	G.arcnum = a;		// 30条边
	// 初始化城市序号
	for (i = 0; i<G.vexnum; ++i) G.vex[i].number = i;

	/*下边是城市名*/
	G.vex[0].city = "乌鲁木齐";
	G.vex[1].city = "西宁";
	G.vex[2].city = "兰州";
	G.vex[3].city = "呼和浩特";
	G.vex[4].city = "北京";
	G.vex[5].city = "天津";
	G.vex[6].city = "沈阳";
	G.vex[7].city = "长春";
	G.vex[8].city = "哈尔滨";
	G.vex[9].city = "大连";
	G.vex[10].city = "西安";
	G.vex[11].city = "郑州";
	G.vex[12].city = "徐州";
	G.vex[13].city = "成都";
	G.vex[14].city = "武汉";
	G.vex[15].city = "上海";
	G.vex[16].city = "昆明";
	G.vex[17].city = "贵州";
	G.vex[18].city = "株洲";
	G.vex[19].city = "南昌";
	G.vex[20].city = "福州";
	G.vex[21].city = "柳州";
	G.vex[22].city = "南宁";
	G.vex[23].city = "广州";
	G.vex[24].city = "深圳";

	/* 这里把所有的边假定为20000,含义是城市间不可到达 */
	for (i = 0; i< G.vexnum; ++i)
		for (j = 0; j< G.vexnum; ++j)
			G.arcs[i][j].adj = 20000;
	/*下边是可直接到达的城市间的距离,由于两个城市间距离是互相的,所以要对图中对称的边同时赋值。*/
	G.arcs[0][2].adj = G.arcs[2][0].adj = 1892;
	G.arcs[1][2].adj = G.arcs[2][1].adj = 216;
	G.arcs[2][3].adj = G.arcs[3][2].adj = 1145;
	G.arcs[2][10].adj = G.arcs[10][2].adj = 676;
	G.arcs[3][4].adj = G.arcs[4][3].adj = 668;
	G.arcs[4][5].adj = G.arcs[5][4].adj = 137;
	G.arcs[5][6].adj = G.arcs[6][5].adj = 704;
	G.arcs[6][7].adj = G.arcs[7][6].adj = 305;
	G.arcs[7][8].adj = G.arcs[8][7].adj = 242;
	G.arcs[6][9].adj = G.arcs[9][6].adj = 397;
	G.arcs[4][11].adj = G.arcs[11][4].adj = 695;
	G.arcs[5][12].adj = G.arcs[12][5].adj = 674;
	G.arcs[10][13].adj = G.arcs[13][10].adj = 842;
	G.arcs[11][14].adj = G.arcs[14][11].adj = 534;
	G.arcs[12][15].adj = G.arcs[15][12].adj = 651;
	G.arcs[13][16].adj = G.arcs[16][13].adj = 1100;
	G.arcs[13][17].adj = G.arcs[17][13].adj = 967;
	G.arcs[14][18].adj = G.arcs[18][14].adj = 409;
	G.arcs[17][18].adj = G.arcs[18][17].adj = 902;
	G.arcs[15][19].adj = G.arcs[19][15].adj = 825;
	G.arcs[18][19].adj = G.arcs[19][18].adj = 367;
	G.arcs[19][20].adj = G.arcs[20][19].adj = 622;
	G.arcs[17][21].adj = G.arcs[21][17].adj = 607;
	G.arcs[18][21].adj = G.arcs[21][18].adj = 672;
	G.arcs[21][22].adj = G.arcs[22][21].adj = 255;
	G.arcs[18][23].adj = G.arcs[23][18].adj = 675;
	G.arcs[23][24].adj = G.arcs[24][23].adj = 140;
	G.arcs[16][17].adj = G.arcs[17][16].adj = 639;
	G.arcs[10][11].adj = G.arcs[11][10].adj = 511;
	G.arcs[11][12].adj = G.arcs[12][11].adj = 349;
}

void narrate() 
{
	int i, k = 0;
	printf("\n*****************欢迎使用最优交通路径程序!***************\n");
	printf("\n城市列表如下:\n\n");
	for (i = 0; i<25; i++)
	{
		printf("(%2d)%-10s", i, G.vex[i].city); /*输出城市列表*/
		k = k + 1;
		if (k % 4 == 0) printf("\n");
	}
}

/** 最短路径函数 */
void ShortestPath(int city) 
{
	int v, w, i, t;
	int final[25];
	int min;
	for (v = 0; v<25; ++v)
	{
		final[v] = 0; 
		D[v] = G.arcs[city][v].adj;	// 所以与该城市有关的距离

		if (D[v]<20000) { P[v][city] = 1; P[v][v] = 1; }
	}
	D[city] = 0; final[city] = 1;	// 将该城市做上标记
	for (i = 0; i<25; ++i)
	{
		min = 20000;
		for (w = 0; w<25; ++w)
			if (!final[w])	// 判断是否为city
				if (D[w]<min){ v = w; min = D[w]; }// 为可到达的城市

		final[v] = 1;	// 可到达

		for (w = 0; w<25; ++w)
			if (!final[w] && ((min + G.arcs[v][w].adj) < D[w]))
			{
				D[w] = min + G.arcs[v][w].adj;
				for (t = 0; t<25; t++) P[w][t] = P[v][t];
				P[w][w] = 1;
			}
	}
}

/** 输出函数 */
void output(int city1, int city2) 
{
	int a, b, c, d, q = 0;
	a = city2;
	if (a != city1)
	{
		printf("\n从%s到%s的最短路径是", G.vex[city1].city, G.vex[city2].city);
		printf("(最短距离为 %dkm.)\n\t", D[a]);
		printf("%s", G.vex[city1].city);
		d = city1;
		for (c = 0; c<25; ++c)
		{
		gate:;	/* 标号,可以作为goto语句跳转的位置 */
			P[a][city1] = 0;
			for (b = 0; b<25; b++)
			{
				if (G.arcs[d][b].adj<20000 && P[a][b])
				{
					printf("-->%s", G.vex[b].city); q = q + 1;
					P[a][b] = 0;
					d = b;
					if (q % 8 == 0) printf("\n");
					goto gate;
				}
			}
		}
	}

}
void main() /*主函数*/
{
	int v0, v1;
	CreateUDN(25, 30);

	narrate();
	printf("\n请选择起点城市(0~24):\n");
	scanf("%d", &v0);
	printf("请选择终点城市(0~24):\n");
	scanf("%d", &v1);
	ShortestPath(v0);  /*计算两个城市之间的最短路径*/
	output(v0, v1);     /*输出结果*/
	printf("\n");
	system("pause");
}

68、八皇后问题

#include <math.h>
#include <stdlib.h>
#include <stdio.h>

#define MAX 8 /* 棋子数及棋盘大小MAXxMAX */
int board[MAX];

/** 印出結果 */
void show_result()
{
	int i;
	for (i = 0; i<MAX; i++)
		printf("(%d,%d)", i, board[i]);
	printf("\n");
}

/** 检查是否在同一直橫斜线上有其它棋子 */
int check_cross(int n)
{
	int i;
	for (i = 0; i<n; i++){
		if (board[i] == board[n] || (n - i) == abs(board[i] - board[n]))return 1;
	}
	return 0;
}

/** 放棋子到棋盘上 */
void put_chess(int n)
{
	int i;
	for (i = 0; i<MAX; i++){
		board[n] = i;
		if (!check_cross(n)){
			if (n == MAX - 1) show_result();/* 找到其中一种放法了...印出結果 */
			else put_chess(n + 1);
		}
	}
}

void main()
{
	puts("The possible placements are:");
	put_chess(0);
	puts("\n Press any key to quit...");
	system("pause");
}

69、骑士巡游


#include <stdlib.h>
#include <stdio.h>

int f[11][11];                      /*定义一个矩阵来模拟棋盘*/
int adjm[121][121];					/*标志矩阵,即对于上述棋盘,依次进行编号
				   1--121(行优先)可以从一个棋盘格i跳到棋盘格j时,adjm[i][j]=1*/

void creatadjm(void);                     /* 创建标志矩阵函数声明 */
void mark(int, int, int, int);            /* 将标志矩阵相应位置置1 */
void travel(int, int);                    /* 巡游函数声明 */
int n, m;                                 /* 定义矩阵大小及标志矩阵的大小 */


int main()
{
	int i, j, k, l;
	printf("Please input size of the chessboard: ");		/*输入矩阵的大小值*/
	scanf("%d", &n);
	m = n*n;
	creatadjm();											/*创建标志矩阵*/
	puts("The sign matrix is:");
	for (i = 1; i <= m; i++)                                /*打印输出标志矩阵*/
	{
		for (j = 1; j <= m; j++)
			printf("%2d", adjm[i][j]);
		printf("\n");
	}

	printf("Please input the knight's position (i,j): ");	/*输入骑士的初始位置*/
	scanf("%d %d", &i, &j);
	l = (i - 1)*n + j;										/*骑士当前位置对应的标志矩阵的横坐标*/
	while ((i>0) || (j>0))									/*对骑士位置的判断*/
	{
		for (i = 1; i <= n; i++)                            /*棋盘矩阵初始化*/
		for (j = 1; j <= n; j++)
			f[i][j] = 0;
		k = 0;												/*所跳步数计数*/
		travel(l, k);										/*从i,j出发开始巡游*/
		puts("The travel steps are:");
		for (i = 1; i <= n; i++)							/*巡游完成后输出巡游过程*/
		{
			for (j = 1; j <= n; j++)
				printf("%4d", f[i][j]);
			printf("\n");
		}

		printf("Please input the knight's position (i,j): ");/*为再次巡游输入起始位置*/
		scanf("%d %d", &i, &j);
		l = (i - 1)*n + j;
	}
	system("pause");
}



/** 创建标志矩阵子函数 **/
void creatadjm()
{
	int i, j;
	/*巡游矩阵初始化*/
	for (i = 1; i <= n; i++)		
		for (j = 1; j <= n; j++)
			f[i][j] = 0;
	/*标志矩阵初始化*/
	for (i = 1; i <= m; i++)		
		for (j = 1; j <= m; j++)
			adjm[i][j] = 0;
	for (i = 1; i <= n; i++)
		/*对所有符合条件的标志矩阵种元素置1*/
		for (j = 1; j <= n; j++)
			if (f[i][j] == 0)				
			{
				f[i][j] = 1;
				if ((i + 2 <= n) && (j + 1 <= n)) mark(i, j, i + 2, j + 1);
				if ((i + 2 <= n) && (j - 1 >= 1)) mark(i, j, i + 2, j - 1);
				if ((i - 2 >= 1) && (j + 1 <= n)) mark(i, j, i - 2, j + 1);
				if ((i - 2 >= 1) && (j - 1 >= 1)) mark(i, j, i - 2, j - 1);
				if ((j + 2 <= n) && (i + 1 <= n)) mark(i, j, i + 1, j + 2);
				if ((j + 2 <= n) && (i - 1 >= 1)) mark(i, j, i - 1, j + 2);
				if ((j - 2 >= 1) && (i + 1 <= n)) mark(i, j, i + 1, j - 2);
				if ((j - 2 >= 1) && (i - 1 >= 1)) mark(i, j, i - 1, j - 2);
			}
}


/** 巡游子函数 */
void travel(int p, int r)
{
	int i, j, q;
	for (i = 1; i <= n; i++)
	for (j = 1; j <= n; j++)
	if (f[i][j]>r) f[i][j] = 0;					/*棋盘矩阵的置〉r时,置0*/
	r = r + 1;									/*跳步计数加1*/
	i = ((p - 1) / n) + 1;						/*还原棋盘矩阵的横坐标*/
	j = ((p - 1) % n) + 1;						/*还原棋盘矩阵的纵坐标*/
	f[i][j] = r;								/*将f[i][j]做为第r跳步的目的地*/


	/* 从所有可能的情况出发,开始进行试探式巡游 */
	for (q = 1; q <= m; q++)          
	{
		i = ((q - 1) / n) + 1;
		j = ((q - 1) % n) + 1;
		if ((adjm[p][q] == 1) && (f[i][j] == 0))
			travel(q, r);						/*递归调用自身*/              
	}
	return;
}

/** 赋值子函数 */
void mark(int i1, int j1, int i2, int j2)
{
	adjm[(i1 - 1)*n + j1][(i2 - 1)*n + j2] = 1;
	adjm[(i2 - 1)*n + j2][(i1 - 1)*n + j1] = 1;
}

70、基于队列、栈的字符串翻译

#include   <stdio.h> 
#include   <string.h> 
#include   <stdlib.h> 
#include   <conio.h> 

/*定义全局变量*/
#define   TRUE   1 
#define   FALSE   0 
#define   OK   1 
#define   ERROR   0 
#define   NULL   0 
#define   OVERFLOW   -2 
#define   MAXSIZE   100 
#define   stack_init_size   100 
#define   stackincrement   10 
typedef   char   selemType;
typedef   char   qelemType;
typedef   char   elemType;
typedef   int   status;
char   e;
char   demon[MAXSIZE];

/* 类型及其基本操作*/
typedef struct
{
	selemType *base;
	selemType *top;
	int stacksize;
}sqstack;

/** 初始化栈 */
status initstack(sqstack *s)
{
	s->base = (selemType *)malloc(stack_init_size*sizeof(selemType));
	if (!s->base)   exit(OVERFLOW);
	s->top = s->base;
	s->stacksize = stack_init_size;
	return   OK;
}

/** 入栈 */
status push(sqstack *s, selemType e)
{
	if (s->top - s->base >= s->stacksize)
	{
		s->base = (elemType*)realloc(s->base, (s->stacksize + stackincrement)*sizeof(elemType));
		if (!s->base)   exit(OVERFLOW);
		s->top = s->base + s->stacksize;
		s->stacksize += stackincrement;
	}
	*(s->top++) = e;
	return   OK;
}

/** 出栈 */
status pop(sqstack   *s, selemType   *e)
{
	if (s->top == s->base)   return   ERROR;
	*e = *(--(s->top));
	return   OK;
}

/** 队列类型及其基本操作 */
typedef struct qnode
{
	qelemType   data;
	struct   qnode   *next;
}qnode, *queueptr;

typedef struct
{
	queueptr   front;
	queueptr   rear;
}linkqueue;

/** 初始化队列 */
status initqueue(linkqueue   *q)
{
	q->front = q->rear = (queueptr)malloc(sizeof(qnode));
	if (!q->front)   exit(OVERFLOW);
	q->front->next = NULL;
	return   OK;
}

/** 入队 */
status enqueue(linkqueue *q, qelemType e)
{
	queueptr   p;
	p = (queueptr)malloc(sizeof(qnode));
	if (!p)   exit(OVERFLOW);
	p->data = e;
	p->next = NULL;
	q->rear->next = p;
	q->rear = p;
	return   OK;
}

/** 出队 */
status dequeue(linkqueue *q, qelemType *e)
{
	queueptr p;
	if (q->front == q->rear) return ERROR;
	p = q->front->next;
	*e = p->data;
	q->front->next = p->next;
	if (q->rear == p)
	{
		q->rear = q->front;
	}
	free(p);
	return   OK;
}

/** 临时栈 */
void tempstack(sqstack *temps)
{
	int   i = 0;
	char   t;
	char   c;
	c = demon[i];
	for (i = 0; c != '#'; i++)	/* 遍历数组 */
	{
		c = demon[i];
		if (c == '(')			/* 遇到开括号 */
		{
			t = demon[i + 1];	/* 取括号中的首字母 */
			push(temps, t);		/* 入栈 */
			i++;				/* 指向首字母 */
			do
			{
				i++;
				c = demon[i];
				push(temps, c)	/* 第一次循环将次字母入栈 */;
				push(temps, t);	/* 再将首字母进栈 */
			} while (c != ')');	/* 直到括号中元素全部进栈 */
			pop(temps, &t);		/* 将多余进栈的首字母t出栈 */
			pop(temps, &t);		/* 将多余进栈的')'出栈 */
		}
	}
}

/** 特殊入队函数 */
void spenqueue(linkqueue   *q, char   key)
{
	int j = 0;
	char a[5];
	switch (key)   /* 判断大写字母对应的字符串 */
	{
		case'A':strcpy(a, "ase"); break;
		case'B':strcpy(a, "tAdA"); break;
		case'C':strcpy(a, "abc"); break;
		case'D':strcpy(a, "def"); break;
		case'E':strcpy(a, "ghi"); break;
		case'F':strcpy(a, "klm"); break;
		case'H':strcpy(a, "mop"); break;
		default:strcpy(a, "???");   /* 不能翻译的魔王语言以"???"输出 */
	}
	while (a[j] != '\0')   /* 如果数组还有字母 */
	{
		enqueue(q, a[j]);/*进队*/
		j++;
	}
}

/** 排序入队处理函数 */
status sort(sqstack   *s, linkqueue   *q)
{
	qnode b;
	int flag = 0;						/* 大写字母监视哨置零 */
	int i;	
	for (i = 0; demon[i] != '#'; i++)	/*遍历数组*/
	{
		b.data = demon[i];
		if (('a' <= b.data&&b.data <= 'z') || b.data == '?')   /* 如果是小写字母或者'?' 则直接进栈 */
		{
			enqueue(q, b.data);
		}
		else
		{
			if ('A' <= b.data&&b.data <= 'Z')   /*如果是大写字母,则调用特殊进栈函数,*/
			{
				spenqueue(q, b.data);
				flag = 1;					/*发现大写字母监视哨置1*/
			}
			else
			{
				if (b.data == '(')			/* 如果是括号 */
				{
					do
					{
						pop(s, &e);
						enqueue(q, e);
					} while (!(s->top == s->base));   /* 只要栈不为空,则出栈进队 */
					while (b.data != ')')	 /* 只要还指向括号内元素,就继续往后移,保证原括号内的元素不再进栈*/
					{
						i++;
						b.data = demon[i];
					}
				}
			}
		}
	}
	return   flag;
}

void main()
{
	sqstack   s1;
	linkqueue   q1;
	int   k = 0;
	int   flag = 1;
	printf("Please Input the Demon's Words:\n");
	printf("!: Less Than 30 Letters: )\n");
	printf("!: End with '#': )\n");
	scanf("%s", demon);
	printf("\n***************************************");
	initstack(&s1);		/* 创建栈 */
	initqueue(&q1);		/* 创建队 */
	tempstack(&s1);		/* 调用函数 */
	while (flag == 1)   /* 如果有大写字母 */
	{
		k = 0;
		flag = sort(&s1, &q1);
		while (q1.front != q1.rear)   /*重写demon[i   ]*/
		{
			dequeue(&q1, &e);
			demon[k] = e;
			k++;
		}
		demon[k] = '#';
	}
	demon[k] = '\0';
	printf("\n***************************************");
	printf("\nThe   Human   Words:\n\t%s", demon);
	printf("\n***************************************");
	system("pause");
}

71、火车车厢重排

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

#define StackSize 100	// 假定预分配的栈空间最多为100个元素 
#define MaxLength  100	// 最大的字符串长度 	
typedef int DataType;	// 假定栈元素的数据类型为整数 	

typedef struct{
	DataType data[StackSize];
	int top;
}SeqStack;

/** 初始化栈 */
void Initial(SeqStack *S)
{
	S->top = -1;
}

/** 判断栈是否为空 */
int IsEmpty(SeqStack *S)
{
	return S->top == -1;
}

/** 判断栈是否满 */
int IsFull(SeqStack *S)
{
	return S->top == StackSize - 1;
}

/** 进栈 */
void Push(SeqStack *S, DataType x)
{
	if (IsFull(S))
	{
		printf("栈上溢"); 
		exit(1);
	}
	S->data[++S->top] = x;//栈顶指针加1后将x入栈
}

/** 出栈 */
DataType Pop(SeqStack *S)
{
	if (IsEmpty(S))
	{
		printf("栈为空"); 
		return -1;
	}
	return S->data[S->top--];// 栈顶元素返回后将栈顶指针减1
}

/** 取栈顶元素 */ 
DataType Top(SeqStack *S)
{
	if (IsEmpty(S))
	{
		printf("栈为空"); 
		exit(1);
	}
	return S->data[S->top];
}

/**
在一个缓冲铁轨中放入车厢c, 为车厢c寻找最优的缓冲铁轨, 初始化
如果没有可用的缓冲铁轨,则返回0,如果空间不足,则引发异常否则返回1

*/
int Hold(int c, int *minH, int *minS, SeqStack H[], int k, int n)
{
	int BestTrack = 0, i;	// 目前最优的铁轨
	int BestTop = n + 1;	// 最优铁轨上的头辆车厢
	int x;					// 车厢索引
	//扫描缓冲铁轨
	for (i = 1; i <= k; i++)

	// 铁轨i 不空
	if (IsEmpty(&H[i]))
	{
		x = Top(&H[i]);
		if (c<x && x < BestTop)
		{//铁轨i 顶部的车厢编号最小
			BestTop = x;
			BestTrack = i;
		}
	}
	else // 铁轨i 为空
	if (!BestTrack)
		BestTrack = i;
	if (!BestTrack)
		return 0; //没有可用的铁轨
	//把车厢c 送入缓冲铁轨
	Push(&H[BestTrack], c);
	printf("Move car %d  from input to holding track %d\n", c, BestTrack);
	//必要时修改minH 和minS
	if (c<*minH) {
		*minH = c;
		*minS = BestTrack;
	}
	return 1;
}

//把车厢从缓冲铁轨送至出轨处,同时修改mins和minh
void Output(int* minH, int* minS, SeqStack H[], int k, int n)
{ 
	int c, i; // 车厢索引
	// 从堆栈m i n S中删除编号最小的车厢minH
	c = Pop(&H[*minS]);
	printf("Move car %d from holding track %d to output\n", *minH, *minS);
	// 通过检查所有的栈顶,搜索新的m i n H和m i n S
	*minH = n + 2;
	for (i = 1; i <= k; i++)
	if (!IsEmpty(&H[i]) && (c = Top(&H[i])) < *minH) {
		*minH = c;
		*minS = i;
	}
}

/**
k个缓冲铁轨,车厢初始排序为p [1:n]; 
如果重排成功,返回1,否则返回0; 如果内存不足,则引发异常NoMem 。
创建与缓冲铁轨对应的堆栈
*/
int Railroad(int p[], int n, int k)
{
	SeqStack *H;
	int NowOut = 1;		// 下一次要输出的车厢
	int minH = n + 1;	// 缓冲铁轨中编号最小的车厢
	int minS, i;		// minH号车厢对应的缓冲铁轨
	H = (SeqStack*)calloc((k + 1), sizeof(SeqStack)*(k + 1));

	/* 车厢重排 */
	for (i = 1; i <= n; i++)
	if (p[i] == NowOut) {
		printf("移动车厢%d从出口到入口", p[i]);// 直接输出t
		NowOut++;
		/* 从缓冲铁轨中输出 */ 
		while (minH == NowOut) {
			Output(&minH, &minS, H, k, n);
			NowOut++;
		}
	}
	// 将p[i] 送入某个缓冲铁轨
	else {
		if (!Hold(p[i], &minH, &minS, H, k, n))
			return 0;
	}
	return 1;
}
void main(void)
{
	int p[8] = { 2, 4, 1, 6, 5, 3, 8, 7 };
	Railroad(p, 8, 4);
	system("pause");
}

72、队列实例

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>

#define MAX 100

char *p[MAX], *qretrieve(void);
int spos = 0;
int rpos = 0;
void enter(void), qstore(char *q), review(void), delete_ap(void);

int main(void)
{
	char s[80];
	register int t;

	for (t = 0; t < MAX; ++t) p[t] = NULL; /* init array to nulls */

	for (;;) {
		printf("Enter, List, Remove, Quit: ");
		gets(s);
		*s = toupper(*s);

		switch (*s) {
		case 'E':
			enter();
			break;
		case 'L':
			review();
			break;
		case 'R':
			delete_ap();
			break;
		case 'Q':
			exit(0);
		}
	}
	system("pause");
	return 0;
}

/** 入队 */
void enter(void)
{
	char s[256], *p;

	do {
		printf("Enter appointment %d: ", spos + 1);
		gets(s);
		if (*s == 0) break; /* no entry */
		p = (char *)malloc(strlen(s) + 1);
		if (!p) {
			printf("Out of memory.\n");
			return;
		}
		strcpy(p, s);
		if (*s) qstore(p);
	} while (*s);
}

/** 查看队列 */
void review(void)
{
	register int t;

	for (t = rpos; t < spos; ++t)
		printf("%d. %s\n", t + 1, p[t]);
}

/** 出队 */
void delete_ap(void)
{
	char *p;

	if ((p = qretrieve()) == NULL) return;
	printf("%s\n", p);
}

/* 入队 */
void qstore(char *q)
{
	if (spos == MAX) {
		printf("List Full\n");
		return;
	}
	p[spos] = q;
	spos++;
}

/* 检索队列 */
char *qretrieve(void)
{
	if (rpos == spos) {
		printf("No more appointments.\n");
		return NULL;
	}
	rpos++;
	return p[rpos - 1];
}

73、K阶斐波那契序列

#include <stdio.h>
#include <stdlib.h>

#define  enoughsize 100  //最大队列长度
typedef struct
{
	int *base;		//初始化的动态分配存储空间
	int front;      //头指针,若队列不空,指向队列头元素
	int rear;		//尾指针,若队列不空,指向队列尾元素的下一个位置
}SqQueue;


int AddSum(int n, int *q)
{
	int sum = 0;
	int i;
	for (i = 0; i<n; i++)  sum += q[i];
	return sum;
}

void main()
{
	SqQueue Q;
	int k, max, i, n, *store;
	printf("请输入斐波那奇的阶数:");
	scanf("%d", &k);
	printf("请输入序列中允许的最大数:");
	scanf("%d", &max);
	Q.base = (int*)malloc(k*sizeof(int));
	store = (int*)malloc(enoughsize*sizeof(int));
	if ((!Q.base) || (!store))
	{
		printf("Error!");
		return;
	}
	for (i = 0; i<k; i++)
	{
		store[i] = 0;
		Q.base[i] = 0;
	}
	store[k - 1] = 1;
	Q.base[k - 1] = 1;   //初始化fib序列
	store[k] = AddSum(k, Q.base);
	Q.front = 0;
	Q.rear = k - 1;
	n = k;
	while (store[n] <= max)
	{
		Q.rear = (Q.rear + 1) % k;
		Q.base[Q.rear] = store[n];
		n++;
		store[n] = AddSum(k, Q.base);
	}
	printf("The first %d%s%d%c%s", n, " numbers are less than ", max, '.', "\n");
	printf("The numbers are:\n");
	for (i = 0; i<n; i++)  printf("%d%c", store[i], ' ');
	printf("\n");

	system("pause");
}

74、绘制余弦曲线和直线的迭加

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

void main()
{
	double y;
	int x, m, n, yy;
	puts("========This program shows the curve of cos(x) and a line.========");
	puts("        ******* f(x)=cos(x)    +++++++ g(x)=45*(y-1)+31");

	/*对于第一个y坐标进行计算并在一行中打印图形*/
	for (yy = 0; yy <= 20; yy++) 
	{
		y = 0.1*yy;							/* y:屏幕行方向坐标 */
		m = acos(1 - y) * 10;				/* m: cos(x)曲线上y点对应的屏幕列坐标 */
		n = 45 * (y - 1) + 31;				/* n: 直线上y点对应的列坐标 */
		for (x = 0; x <= 62; x++)           /*x: 屏幕列方向坐标 */
		if (x == m&&x == n) printf("+");	/* 直线与cos(x)相交时打印"+" */
		else if (x == n) printf("+");		/* 打印不相交时的直线图形 */
		else if (x == m || x == 62 - m) printf("*");  /* 打印不相交时的cos(x)图形 */
		else  printf(" ");					/* 其它情况打印空格 */
		printf("\n");
	}
	system("pause");
}

75、计算高次方数的尾数

#include<stdio.h>
#include<stdlib.h>

void main()
{
	int i, x, y, last = 1;    /* 变量last保存求X的Y次方过程中的部分乘积的后三位 */
	puts("**********************************************************");
	puts("*  This is a program to calculate the last 3 digits of   *");
	puts("*              high order value, e.g., 13^15.            *");
	puts("**********************************************************");
	printf("\n >> Input X and Y(X^Y): ");
	scanf("%d%d", &x, &y);
	for (i = 1; i <= y; i++)                /*X自乘Y次*/
		last = last*x % 1000;     /*将last乘X后对1000取模,即求积的后三位*/
	printf("\n >> The last 3 digits of %d^%d is: %d\n", x, y, last % 1000); /*打印结果*/
	system("pause");
}

76、打鱼还是晒网

#include<stdio.h>
#include<stdlib.h>

struct date{
	int year;
	int month;
	int day;
};
int days(struct date day);

void main()
{
	struct date today, term;
	int yearday, year, day;
	puts("◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇");
	puts("◇              打鱼还是晒网                        ◇");
	puts("◇    中国有句俗语叫【三天打鱼两天晒网】。          ◇");
	puts("◇某人20岁从1990年1月1日起开始【三天打鱼两天晒网】,◇");
	puts("◇问这个人在以后的某一天中是【打鱼】还是【晒网】?  ◇");
	puts("◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇◇\n");
	while (1)
	{
		printf(" >> 请输入年/月/日【输入1990 1 1 退出】:");
		scanf("%d%d%d", &today.year, &today.month, &today.day);  /*输入日期*/
		if (today.year<1990)
		{
			if (today.year<1970)
				puts(" >> 对不起,那一年那还没出生呢!按任意键继续...");
			else
				puts(" >> 对不起,那一年他还没开始打鱼呢!按任意键继续...");
			getchar();
			continue;
		}
		if (today.year == 1990 && today.month == 1 && today.day == 1)
			break;
		term.month = 12;               /*设置变量的初始值:月*/
		term.day = 31;                 /*设置变量的初始值:日*/
		for (yearday = 0, year = 1990; year<today.year; year++)
		{
			term.year = year;
			yearday += days(term);     /*计算从1990年至指定年的前一年共有多少天*/
		}
		yearday += days(today);       /*加上指定年中到指定日期的天数*/
		day = yearday % 5;               /*求余数*/
		if (day>0 && day<4) printf(" >> %d年%d月%d日,他正在打鱼。\n", today.year, today.month, today.day);   /*打印结果*/
		else printf(" >> %d年%d月%d日,他正在晒网。\n", today.year, today.month, today.day);

	}
	system("pause");
}

int days(struct date day)
{
	static int day_tab[2][13] =
	{ { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, },      /*平均每月的天数*/
	{ 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, },
	};
	int i, lp;
	lp = day.year % 4 == 0 && day.year % 100 != 0 || day.year % 400 == 0;
	/*判定year为闰年还是平年,lp=0为平年,非0为闰年*/
	for (i = 1; i<day.month; i++)            /*计算本年中自1月1日起的天数*/
		day.day += day_tab[lp][i];
	return day.day;
}

77、怎样存钱以获取最大利息

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

void main()
{
	int i8, i5, i3, i2, i1, n8, n5, n3, n2, n1;
	float max = 0, term;

	/* 穷举所有可能的存款方式 */
	for (i8 = 0; i8<3; i8++)       
	for (i5 = 0; i5 <= (20 - 8 * i8) / 5; i5++)
	for (i3 = 0; i3 <= (20 - 8 * i8 - 5 * i5) / 3; i3++)
	for (i2 = 0; i2 <= (20 - 8 * i8 - 5 * i5 - 3 * i3) / 2; i2++)
	{
		i1 = 20 - 8 * i8 - 5 * i5 - 3 * i3 - 2 * i2;
		term = 2000.0*pow((double)(1 + 0.0063 * 12), (double)i1)
			*pow((double)(1 + 2 * 0.0063 * 12), (double)i2)
			*pow((double)(1 + 3 * 0.0069 * 12), (double)i3)
			*pow((double)(1 + 5 * 0.0075 * 12), (double)i5)
			*pow((double)(1 + 8 * 0.0084 * 12), (double)i8);

		/* 计算到期时的本利合计 */
		if (term>max)
		{
			max = term; n1 = i1; n2 = i2; n3 = i3; n5 = i5; n8 = i8;
		}
	}
	printf("For maxinum profit,he should so save his money in a bank:\n");
	printf("   made fixed deposit for 8 year: %d times\n", n8);
	printf("   made fixed deposit for 5 year: %d times\n", n5);
	printf("   made fixed deposit for 3 year: %d times\n", n3);
	printf("   made fixed deposit for 2 year: %d times\n", n2);
	printf("   made fixed deposit for 1 year: %d times\n", n1);
	printf("                            Toal: %.2f\n", max);
	/*输出存款方式*/
	system("pause");
}

78、阿姆斯特朗数

#include<stdio.h>
#include<stdlib.h>
#define MAX 255

void main()
{
	int i, j, t, k, m, a[MAX];
	long n;
	puts("     This program will find the Armstrong number.\n");
	printf(" >> Please input the range you want to find (2~n):\n >> ");
	scanf("%ld", &n);
	m = n;
	j = 10;
	while (m >= 10)
	{
		m = m / 10;
		j *= 10;
	}
	printf(" >> There are follwing Armstrong number smaller than %d:\n", n);
	for (i = 2; i<n; i++)         /*穷举要判定的数i的取值范围2~1000*/
	{
		for (t = 0, k = 10; k <= j; t++)     /*截取整数i的各位(从高向低位)*/
		{
			a[t] = (i%k) / (k / 10);        /*分别赋于a[0]~a[2}*/
			k *= 10;
		}
		for (m = 0, t--; t >= 0; t--)
			m += a[t] * a[t] * a[t];
		if (m == i)
			/*判断i是否为阿姆斯特朗数*/
			printf("%5d", i);            /*若满足条件,则输出*/

	}
	system("pause");
}

79、亲密数

#include<stdio.h>
#include<stdlib.h>

void main()
{
	int a, i, b, n, m;
	printf("================================================================\n");
	printf("     This is a program to find friendly numbers pair.\n");
	printf("   Which means the sum of integer A's all factors (except A)\n");
	printf("    equals to the sum of integer B's all factors (except B).\n");
	printf("     < e.g. sum of integer 6's all factors are:1+2+3=6 >\n");
	printf("================================================================\n");
	printf("\n Please input the scale you want to find n: ");
	scanf("%d", &n);
	printf("\n There are following friendly--numbers pair smaller than %d:\n", n);
	for (a = 1; a<n; a++)        /*穷举1000以内的全部整数*/
	{
		for (b = 0, i = 1; i <= a / 2; i++)    /*计算数a的各因子,各因子之和存放于b*/
		if (!(a%i))b += i;        /*计算b的各因子,各因子之和存于m*/
		for (m = 0, i = 1; i <= b / 2; i++)
		if (!(b%i))m += i;
		if (m == a&&a<b)
			printf("%4d..%4d    ", a, b);     /*若n=a,则a和b是一对亲密数,输出*/
	}
	system("pause");
}

80、自守数

#include<stdio.h>
#include<stdlib.h>

void main()
{
	long mul, number, k, ll, kk, n;
	puts("============================================================");
	puts("||    This program will find the automorphic numbers.     ||");
	puts("|| The defination of a automorphic number is: the mantissa||");
	puts("||     of a natural number's square equals to itself.     ||");
	puts("||       e.g., 25^2=625, 76^2=5776, 9376^2=87909376.      ||");
	puts("============================================================");
	printf("\n >> Please input the scale n you want to find : ");
	scanf("%ld", &n);
	printf("\n >> The automorphic numbers small than %ld are:\n\n", n);
	for (number = 0; number<n; number++)
	{
		for (mul = number, k = 1; (mul /= 10)>0; k *= 10);
		/*由number的位数确定截取数字进行乘法时的系数k*/
		kk = k * 10;      /*kk为截取部分积时的系数*/
		mul = 0;        /*积的最后n位*/
		ll = 10;        /*ll为截取乘数相应位时的系数*/
		while (k>0)
		{
			mul = (mul + (number % (k * 10))*(number%ll - number % (ll / 10))) % kk;
			/*(部分积+截取被乘数的后N位*截取乘数的第M位),%kk再截取部分积*/
			k /= 10;               /*k为截取被乘数时的系数*/
			ll *= 10;
		}
		if (number == mul)         /*判断若为自守数则输出*/
			printf("%ld   ", number);
	}
	system("pause");
}

81、具有abcd=(ab+cd)2性质的数

#include<stdio.h>
#include<stdlib.h>
#include<stdio.h>

void main()
{
	int n, a, b;
	puts("==========================================================");
	puts("||  This program will find the four figures which have  ||");
	puts("||     the characteristic as follows: abcd=(ab+cd)^2.   ||");
	puts("||            e.g., 3025=(30+25)*(30+25).               ||");
	puts("==========================================================");
	printf("\n >> There are following numbers with satisfied condition:\n\n");
	for (n = 1000; n<10000; n++)				/* 四位数N的取值范围1000~9999 */
	{
		a = n / 100;							/* 截取N的前两位数存于a */
		b = n % 100;							/* 截取N的后两位存于b */
		if ((a + b)*(a + b) == n)				/* 判断N是否为符合题目所规定的性质的四位数 */
			printf(" %d  ", n);
	}
	system("pause");
}

82、验证歌德巴赫猜想

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

/* 判断是否为素数 */
int IsPrime(int i)
{
	int j;
	// 是否满足条件
	if (i <= 1) return 0;
	if (i == 2) return 1;
	if (!(i % 2)) return 0;  

	for (j = 3; j <= (int)(sqrt((double)i) + 1); j += 2)
		if (!(i%j)) return 0;
	return 1;              
}

/* 任何正偶数都可以分解成两个质数的和   */
void main()
{
	int i, j, n;
	long max;
	puts("============================================================");
	puts("||       This program will verify the Goldbach Guess.     ||");
	puts("|| That is any positive even number can be broken up into ||");
	puts("||               the sum of two prime numbers.            ||");
	puts("||       e.g., 4=2+2, 6=3+3, 8=3+5, 10=3+7, 12=5+7,...    ||");
	puts("============================================================");
	printf("\n >> Please input the scale n you want to verify : ");
	scanf("%ld", &max);
	printf("\n >> Now the program starts to verify the even number\n");
	printf(" >> less than %ld equals to sum of two prime numbers.\n\n", max);
	for (i = 4, j = 0; i <= max; i += 2)
	{
		/* 将偶数i分解为两个整数 */
		for (n = 2; n<i; n++)			
			/* 分别判断两个整数是否均为素数 */
			if (IsPrime(n))					 
				if (IsPrime(i - n))
				{
					printf("%4d=%2d+%2d ", i, n, i - n);        /* 若均是素数则输出 */
					j++;
					if (j == 5)
					{
						printf("\n");
						j = 0;
					}
					break;
			}
		if (n == i)  printf("error %d\n", i);
	}
	system("pause");
}

83、素数幻方

int number[210][5];     /* 存放可逆素数及素数分解后的各位数字 */
int select[110];        /* 可以放在矩阵第一行和最后一行的素数的下标 */
int array[4][5];        /* 4X4的矩阵,每行0号元素存可逆素数对应的数组下标 */
int count;              /* 可逆素数的数目 */
int selecount;          /* 可以放在矩阵第一行和最后一行的可逆素数的数目 */
int larray[2][200];     /* 存放素数前二、三位数的临时数组所对应的数量计数器 */
int lcount[2];

/* 函数声明 */
int num(int number); 
int ok(int number);
void process(int i);
void copy_num(int i);
int comp_num(int n);
int find1(int i);
int find2(void);
int find0(int num);
void p_array(void);

FILE *fp;

void main()
{
	int i, k, flag, cc = 0, i1, i4;
	if ((fp = fopen("Exa70data.dat", "w+")) == NULL)
	{
		printf("\n Can't create file Exa70data.dat !\n");
		exit(0);
	}
	printf("there are magic squares with invertable primes as follw:\n");
	for (i = 1001; i<9999; i += 2)                  /* 求满足条件的可逆素数 */
	{
		k = i / 1000;
		if (k % 2 != 0 && k != 5 && num(i))			/* 若可逆素数的第一位不是偶数或5 */
		{
			number[count][0] = i;					/* 存入数组 */
			process(count++);						/* 分解素数的各位数字 */
			if (number[count - 1][2] % 2 != 0 &&    /* 若可逆素数满足放在矩阵第一行 */
				number[count - 1][3] % 2 != 0 &&    /* 和最后一行的条件,记录可逆素数的 */
				number[count - 1][2] != 5 &&		/* 下标,计数器加1 */
				number[count - 1][3] != 5)
				select[selecount++] = count - 1;
		}
	}
	larray[0][lcount[0]++] = number[0][0] / 100;     /* 临时数组的第一行存前二位 */
	larray[1][lcount[1]++] = number[0][0] / 10;      /* 临时数组的第二行存前三位 */
	/* 将素数不重复的前二、三位存入临时数组中 */
	for (i = 1; i<count; i++)						 
	{
		if (larray[0][lcount[0] - 1] != number[i][0] / 100)
			larray[0][lcount[0]++] = number[i][0] / 100;
		if (larray[1][lcount[1] - 1] != number[i][0] / 10)
			larray[1][lcount[1]++] = number[i][0] / 10;
	}
	for (i1 = 0; i1<selecount; i1++)                    /* 在第一行允许的汇聚围内穷举 */
	{
		array[0][0] = select[i1];						/* 取对应的素数下标 */
		copy_num(0);									/* 复制分解的素数 */
		for (array[1][0] = 0; array[1][0]<count; array[1][0]++)    /* 穷举第二行 */
		{
			copy_num(1);                /* 复制分解的数字 */
			if (!comp_num(2))
				continue;         /* 若每列的前两位的组成与素数相矛盾,则试探下一个数 */
			for (array[2][0] = 0; array[2][0]<count; array[2][0]++)     /* 穷举第三行 */
			{
				copy_num(2);           /* 复制分解的数字 */
				if (!comp_num(3))
					continue;          /* 若每列的前三位的组成与素数相矛盾,则试探下一个数 */
				for (i4 = 0; i4<selecount; i4++)     /* 在最后一行允许的范围内穷举 */
				{
					array[3][0] = select[i4];
					copy_num(3);					 /* 复制分解的数字 */
					for (flag = 1, i = 1; flag&&i <= 4; i++)    /* 判断每列是否可逆素数 */
					if (!find1(i))flag = 0;
					if (flag&&find2())				 /* 判断对角线是否为可逆素数 */
					{
						printf("No.%d\n", ++cc);
						fprintf(fp, "No.%d\n", cc);
						p_array();
					}    /* 输出幻方矩阵 */
				}
			}
		}
	}
	fclose(fp);
	system("pause");
}

/* 判断是否可逆素数 */
int num(int number)              
{
	int j;
	if (!ok(number)) return 0;

	for (j = 0; number>0; number /= 10)     /* 将素数变为反序数 */
		j = j * 10 + number % 10;

	if (!ok(j)) return 0;					/* 判断反序数是否为素数 */
	return 1;
}

/* 判断是否为素数 */
int ok(int number)                
{
	int i, j;
	if (number % 2 == 0) return 0;

	j = sqrt((double)number) + 1;

	for (i = 3; i <= j; i += 2)
		if (number%i == 0) return 0;
	return 1;
}

/* 将第i个整数分解为数字并存入数组 */
void process(int i)                 
{
	int j, num;
	num = number[i][0];
	for (j = 4; j >= 1; j--, num /= 10)
		number[i][j] = num % 10;
}

/* 将array[i][0]指向的素数的各位数字复制到array[i]中 */
void copy_num(int i)        
{
	int j;
	for (j = 1; j <= 4; j++)
		array[i][j] = number[array[i][0]][j];
}

/* 判断array中每列的前n位是否与可逆素数允许的前n位矛盾 */
int comp_num(int n)           
{
	static int ii;           /* 用内部静态变量保存前一次查找到的元素下标 */
	static int jj;			 /* ii:前一次查找前二位的下标,jj:前一次查找前三位的下标 */
	int i, num, k, *p;		 /* p:指向对应的要使用的前一次下标ii或jj */
	int *pcount;			 /* pcount:指向要使用的临时数组数量的计数器 */
	switch (n){              /* 根据n的值选择对应的一组控制变量 */
		case 2:pcount = &lcount[0]; p = &ii; break;
		case 3:pcount = &lcount[1]; p = &jj; break;
		default:return 0;
	}
	/* 对四列分别进行处理 */
	for (i = 1; i <= 4; i++)          
	{
		for (num = 0, k = 0; k<n; k++)       /* 计算前n位数字代表的数值 */
			num = num * 10 + array[k][i];
		if (num <= larray[n - 2][*p])        /* 与前一次最后查找到的元素进行比较 */
		for (; *p >= 0 && num<larray[n - 2][*p]; (*p)--);/* 若前次查找到的元素大,则向前找 */
		else
		for (; p<pcount&&num>larray[n - 2][*p]; (*p)++);  /* 否则向后找 */
		if (*p<0 || *p >= *pcount)
		{
			*p = 0; return 0;
		}
		if (num != larray[n - 2][*p])
			return 0;            /* 前n位不是可逆素数允许的值则返回0 */
	}
	return 1;
}

/* 判断列方向是否是可逆素数 */
int find1(int i)               
{
	int num, j;
	for (num = 0, j = 0; j<4; j++)
		num = num * 10 + array[j][i];
	return find0(num);
}

/* 判断对角线方向是否是可逆素数 */
int find2(void)                
{
	int num1, num2, i, j;
	for (num1 = 0, j = 0; j<4; j++)
		num1 = num1 * 10 + array[j][j + 1];
	for (num2 = 0, j = 0, i = 4; j<4; j++, i--)
		num2 = num2 * 10 + array[j][i];
	if (find0(num1)) return(find0(num2));
	else return 0;
}

/* 查找是否为满足要求的可逆素数 */
int find0(int num)               
{
	static int j;
	if (num <= number[j][0])for (; j >= 0 && num<number[j][0]; j--);
	else for (; j<count&&num>number[j][0]; j++);
	if (j<0 || j >= count){ j = 0; return 0; }
	if (num == number[j][0]) return 1;
	else return 0;
}

/* 输出矩阵 */
void p_array(void)                
{
	int i, j;
	for (i = 0; i<4; i++)
	{
		for (j = 1; j <= 4; j++)
		{
			printf("%d ", array[i][j]);
			fprintf(fp, "%d ", array[i][j]);
		}
		printf("\n");
		fprintf(fp, "\n");
	}
}

84、百钱百鸡问题

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<stdio.h>

void main()
{
	int x, y, z, j = 0;
	puts("************************************************");
	puts("*      This program is to solve Problem of     *");
	puts("*           Hundred Yuan Hundred Fowls.        *");
	puts("*  Which is presented by Zhang Qiujiang,       *");
	puts("* a Chinese ancient mathematician, in his work *");
	puts("* Bible of Calculation: 5 Yuan can buy 1 cock, *");
	puts("* 3 Yuan can buy 1 hen, 1 Yuan buy 3 chickens, *");
	puts("* now one has 100 Yuan to buy 100 fowls, the   *");
	puts("* question is how many cocks, hens, chickens   *");
	puts("* to buy?                                      *");
	puts("************************************************");
	printf("\nThe possible plans to buy 100 fowls with 100 Yuan are:\n\n");
	for (x = 0; x <= 20; x++)               /* 外层循环控制鸡翁数 */
	for (y = 0; y <= 33; y++)				/* 内层循环控制鸡母数y在0~33变化 */
	{
		z = 100 - x - y;					/* 内外层循环控制下,鸡雏数z的值受x,y的值的制约 */
		if (z % 3 == 0 && 5 * x + 3 * y + z / 3 == 100)
			/* 验证取z值的合理性及得到一组解的合理性 */
			printf("%2d: cock=%2d hen=%2d chicken=%2d\n", ++j, x, y, z);
	}
	system("pause");
}

85、爱因斯坦数学题

#include<stdio.h>
#include<stdlib.h>

void main()
{
	int i = 1;                  /*i为所设的阶梯数*/
	puts("**************************************************");
	puts("*        This program is to solve                *");
	puts("*     Einstein's interesting math question,      *");
	puts("*   which is presented by Albert Einstein,       *");
	puts("*       a famous theoretical physicist.          *");
	puts("* The Problem is as follows: there is a long     *");
	puts("* ladder, if one step strides 2 stages, 1 stages *");
	puts("* left, if one step strides 3 stages, 2 stages   *");
	puts("* left, if one step strides 5 stages, 4 stages   *");
	puts("* left, if one step strides 7 stages, 0 stages   *");
	puts("* left, the question is, how many stages has     *");
	puts("* the ladder?                                    *");
	puts("**************************************************");
	while (!((i % 2 == 1) && (i % 3 == 2) && (i % 5 == 4) && (i % 6 == 5) && (i % 7 == 0)))
		++i;                  /*满足一组同余式的判别*/
	printf("\n >> The ladder has %d stages.\n", i);
	system("pause");
}

86、三色球问题


#include<stdio.h>
#include<stdlib.h>

void main()
{
	int i, j, count = 0;
	puts("****************************************************************");
	puts("*     This program is to solve Problem of Three Color Ball.    *");
	puts("* The Problem is as follows: There are 12 balls in the pocket. *");
	puts("* Amony them, 3 balls are red,3 balls are white and 6 balls    *");
	puts("* are black. Now take out any 8 balls from the pocket,how      *");
	puts("* many color combinations are there?                           *");
	puts("****************************************************************");
	puts(" >> The solutions are:");
	printf("  No.     RED BALL  WHITE BALL   BLACK BALL\n");
	printf("-----------------------------------------------------\n");
	for (i = 0; i <= 3; i++)               /*循环控制变量i控制任取红球个数0 ̄3*/
	for (j = 0; j <= 3; j++)           /*循环控制变量j控制任取白球个数0 ̄3*/
	if ((8 - i - j) <= 6)
		printf(" %2d    |     %d     |    %d    |     %d\n", ++count, i, j, 8 - i - j);

	printf("-----------------------------------------------------\n");
	system("pause");
}

87、马克思手稿中的数学题

#include<stdio.h>
#include<stdlib.h>
void main()
{
	int x, y, z, count = 0;
	puts("****************************************************************");
	puts("*  This program is to solve an interesting math question in    *");
	puts("*                  Karl Marx's manuscript.                     *");
	puts("* The Problem is as follows: 30 persons spent 50 yuan in a     *");
	puts("* restaurant, amony them, each man spent 3 yuan, each woman    *");
	puts("* spent 2 yuan, and each child spent 1 yuan. The question is   *");
	puts("* how many men, women and children are there?                  *");
	puts("****************************************************************");
	puts(" >> The solutions are:");
	printf("   No.        Men       Women     Children\n");
	printf("---------------------------------------------\n");
	for (x = 0; x <= 10; x++)
	{
		y = 20 - 2 * x;                     /* x定值据(3)式求y */
		z = 30 - x - y;                     /* 由(1)式求z */
		if (3 * x + 2 * y + z == 50)        /* 当前得到的一组解是否满足式(2) */
			printf(" <%2d>    |    %2d    |    %2d    |    %2d\n", ++count, x, y, z);
	}
	printf("---------------------------------------------\n");
	system("pause");
}

88、配对新郎和新娘

#include<stdio.h>
#include<stdlib.h>
void main()
{
	int x, y, z;
	puts("****************************************************************");
	puts("*  This program is to solve Problem of Bridegroom and Bride.   *");
	puts("* The Problem is as follows: Someone goes to 3 couples lovers' *");
	puts("* wedding. The bridegrooms are A,B,C and the brides are X,Y,Z. *");
	puts("* He wants to know who marries who and asks them. A says he    *");
	puts("* will marry to X, X says her fiance is C, C says he will marry*");
	puts("* to Z. The man knows that they are all kidding. What they said*");
	puts("* is not true. So try to find who will marry to who?           *");
	puts("****************************************************************");
	puts(" >> The solutions are:");
	printf("---------------------------------------------\n");
	for (x = 1; x <= 3; x++)			/* 穷举x的全部可能配偶 */
		for (y = 1; y <= 3; y++)		/* 穷举y的全部可能配偶 */
			for (z = 1; z <= 3; z++)    /* 穷举z的全部可能配偶 */
				if (x != 1 && x != 3 && z != 3 && x != y&&x != z&&y != z)  /* 判断配偶是否满足题意 */
				{
					printf(" X will marry to %c.\n", 'A' + x - 1);  
					printf(" Y will marry to %c.\n", 'A' + y - 1);
					printf(" Z will marry to %c.\n", 'A' + z - 1);
				}
	printf("---------------------------------------------\n");
	system("pause");
}

89、邮票组合

#include<stdio.h>
#include<stdlib.h>
#define M 255
int a[M];

void main()
{
	int i, j, k, s, n = 0;
	puts("****************************************************************");
	puts("*    This program is to solve Problem of Stamp Combination.    *");
	puts("* The Problem is as follows. John has 4 stamps with value of 3 *");
	puts("* cents and 3 stamps with value of 5 cents. Use one or more of *");
	puts("* these stamps, how many kinds of postages can John provide?   *");
	puts("****************************************************************");
	puts("\n >> The solution is: \n");
	printf("---------------------------------------------\n\n");
	for (i = 0; i <= 4; i++)            /* i:取三分邮票的张数 */
		for (j = 0; j <= 3; j++)		/* j:取5分邮票的张数 */
		{
			s = i * 3 + j * 5;			/* 计算组成的邮票面值 */
			for (k = 0; a[k]; k++)      /* 查找是否有相同的邮资 */
			if (s == a[k])break;
			if (!a[k] && s)				/* 没有找到相同的邮资则满足要求存入数组 */
			{
				a[k] = s; n++;
			}
		}
	printf(" >> There are %d kinds of postages:\n\n", n);      /* 输出结果 */
	for (k = 0; a[k]; k++)
		printf(" %d", a[k]);
	printf("\n");
	printf("\n---------------------------------------------\n");
	system("pause");
}

90、分糖果

#include<stdio.h>
#include<stdlib.h>

void print(int s[]);
int judge(int c[]);
int j = 0;

void main()
{
	static int sweet[10] = { 10, 2, 8, 22, 16, 4, 10, 6, 14, 20 };   /*初始化数组数据*/
	int i, t[10], l;
	printf("  Child No.    1   2   3   4   5   6   7   8   9   10\n");
	printf("------------------------------------------------------\n");
	printf("  Round No.|\n");
	print(sweet);          /*输出每个人手中糖的块数*/
	while (judge(sweet))      /*若不满足要求则继续进行循环*/
	{
		for (i = 0; i<10; i++)    /*将每个人手中的糖分成一半*/
		if (sweet[i] % 2 == 0)     /*若为偶数则直接分出一半*/
			t[i] = sweet[i] = sweet[i] / 2;
		else               /*若为奇数则加1后再分出一半*/
			t[i] = sweet[i] = (sweet[i] + 1) / 2;
		for (l = 0; l<9; l++)         /*将分出的一半糖给右(后)边的孩子*/
			sweet[l + 1] = sweet[l + 1] + t[l];
		sweet[0] += t[9];
		print(sweet);             /*输出当前每个孩子中手中的糖数*/
	}
	printf("------------------------------------------------------\n");
	system("pause");
}

int judge(int c[])
{
	int i;
	for (i = 0; i<10; i++)          /*判断每个孩子手中的糖是否相同*/
	if (c[0] != c[i]) return 1;          /*不相同返回 1*/
	return 0;
}

void print(int s[])      /*输出数组中每个元素的值*/
{
	int k;
	printf("      <%2d> | ", j++);
	for (k = 0; k<10; k++)   printf("%4d", s[k]);
	printf("\n");
}

91、波瓦松的分酒趣题

#include<stdio.h>
#include<stdlib.h>

void getti(int a, int y, int z);
int i;           /* 最后需要分出的重量 */

void main()
{
	int a, y, z;
	puts("***************************************************************");
	puts("*  This program is to solve Problem of Poisson Beer Division. *");
	puts("* The Problem is as follows: Someone has a bottle of 12 pints *");
	puts("* beer. He wants to get 6 pints, but he does not has a bottle *");
	puts("* of 6 pints. He only has a bottle of 8 pints and a bottle of *");
	puts("* 5 pints. So how can he get 6 pints?                         *");
	puts("***************************************************************");
	printf(" >> Input Full bottle a,Empty b,c, and Get volumes:\n"); /* a 满瓶的容量  y:第一个空瓶的容量  z:第二个空瓶的容量 */
	printf(" >> ");
	scanf("%d%d%d%d", &a, &y, &z, &i);
	getti(a, y, z);           /*按a -> y -> z -> a的操作步骤*/
	/*getti(a,z,y);           /*按a -> z -> y -> a的步骤*/
	system("pause");
}

/* a:满瓶的容量  y:第一个空瓶的容量  z:第二个空瓶的容量 */
void getti(int a, int y, int z)   
{
	int b = 0, c = 0, j = 0;			 /* b:第一瓶实际的重量  c:第二瓶实际的重量 j: 倒的步数 */
	puts(" >> The division steps are as follows.\n");

	printf(" Bottle:    a<%d> b<%d> c<%d>\n", a, y, z);
	printf("-----------------------------\n");
	printf(" Step No.|\n");
	printf("   <%d>   | %4d %4d %4d\n", j++, a, b, c);

	/* 当满瓶!=i或另两瓶都!=i */
	while (a != i || b != i&&c != i)      
	{
		if (!b)
		{
			a -= y; b = y;
		}    /* 如果第一瓶为空,则将满瓶倒入第一瓶中 */
		else if (c == z)
		{
			a += z; c = 0;
		}    /* 如果第二瓶满,则将第二瓶倒入满瓶中 */
		else if (b>z - c)    /* 如果第一瓶的重量>第二瓶的剩余空间 */
		{
			b -= (z - c); c = z;
		}    /* 则将装满第二瓶,第一瓶中保留剩余部分 */
		else{ c += b; b = 0; }   /* 否则,将第一瓶全部倒入第二瓶中 */
		printf("   <%d>   | %4d %4d %4d\n", j++, a, b, c);
	}
	printf("-----------------------------\n");
}

92、求π的近似值

#include<stdio.h>
#include<math.h>
#include<time.h>
#include<stdlib.h>
#define N 30000

void main()
{
	double e = 0.1, b = 0.5, c, d;
	long int i;                /*i: 正多边形边数*/
	float x, y;
	int c2 = 0, d2 = 0;
	puts("***********************************************************");
	puts("*      This program is to calculate PI approximatively    *");
	puts("*                    in two methods.                      *");
	puts("*       One method is Regular Polygon Approximating,      *");
	puts("*          the other is Random Number Method.             *");
	puts("***********************************************************");
	puts("\n >> Result of Regular Polygon Approximating:");
	for (i = 6;; i *= 2)            /*正多边形边数加倍*/
	{
		d = 1.0 - sqrt(1.0 - b*b);     /*计算圆内接正多边形的边长*/
		b = 0.5*sqrt(b*b + d*d);
		if (2 * i*b - i*e<1e-15) break;         /*精度达1e-15则停止计算*/
		e = b;      /*保存本次正多边形的边长作为下一次精度控制的依据*/
	}
	printf("---------------------------------------------------------\n");
	printf(" >> pi=%.15lf\n", 2 * i*b);       /*输出π值和正多边形的边数*/
	printf(" >> The number of edges of required polygon:%ld\n", i);
	printf("---------------------------------------------------------\n");
	srand(time(0));
	while (c2++ <= N)
	{
		x = rand() % 100;      /*x:坐标。产生0到100之间共101个的随机数*/
		y = rand() % 100;      /*y:坐标。产生0到100之间共101个的随机数*/
		if (x*x + y*y <= 10000)     /*利用圆方程判断点是否落在圆内*/
			d2++;
	}
	puts("\n >> Result of Random Number Method:");
	printf("---------------------------------------------------------\n");
	printf(" >> pi=%f\n", 4.*d2 / N);    /*输出求出的π值*/
	printf("---------------------------------------------------------\n");
	system("pause");
}

93、奇数平方的有趣性质

#include<stdio.h>
#include<stdlib.h>

void main()
{
	long int a, n = 0;
	puts("***********************************************************");
	puts("*      >>      This program is to verify       <<         *");
	puts("*      >>     odd number's characteristic.     <<         *");
	puts("* That is square of an odd number larger than 1000 minus  *");
	puts("* 1 can be divided exactly by 8.                          *");
	puts("* For example, 2001^2-1=4004000=500500*8.                 *");
	puts("***********************************************************");
	while (n<1001)
	{
		printf(" >> Please input the range you want to verify: ");
		scanf("%ld", &n);
	}
	puts(" >> Now start to verify:");
	for (a = 1001; a <= n; a += 2)
	{
		printf("%ld:", a);						/* 输出奇数本身 */
		printf("(%ld*%ld-1)/8", a, a);			/* 输出(奇数的平方减1)/8 */
		printf("=%ld", (a*a - 1) / 8);			/* 输出被8除后的商 */
		printf("+%ld\n", (a*a - 1) % 8);		/* 输出被8除后的余数 */
	}
	system("pause");
}

94、角谷猜想

#include<stdio.h>
#include<stdlib.h>


void main()
{
	int n = 1, count = 0;
	puts("*********************************************************");
	puts("*      >> This program is to verify Jiaogu Guess  <<    *");
	puts("* That is given any natural number, if it is an even,   *");
	puts("* divides 2, if it is an odd, multiple 3 and add 1, the *");
	puts("* result continues to be calculated analogously. After  *");
	puts("* some times, the result is always 1.                   *");
	puts("*********************************************************");
	while (n != 0)
	{
		printf(" >> Please input a number to verify(0 to quit): ");
		scanf("%d", &n);      /* 输入任一整数 */
		if (n == 0)
			break;
		printf(" >> ------ Results of verification: ------------\n");
		do{
			if (n % 2)
			{
				n = n * 3 + 1;           /* 若为奇数,n乘3加1 */
				printf(" >> Step No.%d: %d*3+1=%d\n", ++count, (n - 1) / 3, n);
			}
			else
			{
				n /= 2;          /* 若为偶数n除以2 */
				printf(" >> Step No.%d: %d/2=%d\n", ++count, 2 * n, n);
			}
		} while (n != 1);             /* n不等于1则继续以上过程 */
		printf(" >> ---------------------------------------------\n");
	}
	system("pause");
}

95、四方定理

#include<stdio.h>
#include<stdlib.h>

void verify_four_squares(int number)
{
	int i, j, k, l;
	for (i = 1; i<number / 2; i++)         /*试探法。试探i,j,k,k的不同值*/
	for (j = 0; j <= i; j++)
	for (k = 0; k <= j; k++)
	for (l = 0; l <= k; l++)
	if (number == i*i + j*j + k*k + l*l)    /*若满足定理要求则输出结果*/
	{
		printf(" >> %d=%d*%d+%d*%d+%d*%d+%d*%d\n", number, i, i, j, j, k, k, l, l);
		return;
	}
}
void main()
{
	int number = 1;

	puts("*****************************************************");
	puts("* This program is to verify Theorem of Four Squares.*");
	puts("* That is all natural numbers can be represented as *");
	puts("* sum of no more than 4 squares of the numbers.     *");
	puts("*****************************************************");
	while (number != 0)
	{
		printf(" >> Please input a number to verify(0 to quit): ");
		scanf("%d", &number);      /* 输入任一整数 */
		if (number == 0)
			break;
		printf(" >> ------ Results of verification: ------------\n");
		verify_four_squares(number);
		printf(" >> ---------------------------------------------\n");
	}
	system("pause");
}

96、卡布列克常数

#include<stdio.h>
#include<stdlib.h>

void vr6174(int);
void parse_sort(int num, int *each);
void max_min(int *each, int *max, int *min);
void parse_sort(int num, int *each);
int count = 0;
void main()
{

	int n = 1;
	puts("**************************************************************");
	puts("*         This program is to verify Comgrich Content.        *");
	puts("* That is any 4-digit number whose digitals are not the same *");
	puts("* has the rule: (1) range the 4 digits to get the maximum    *");
	puts("* 4-digit number, (2) range the 4 digits to get the minimum  *");
	puts("* 4-digit number, (3) get the difference of these two numbers*");
	puts("* that is a new 4-digit number. Continute to calculate with  *");
	puts("* (1)-(3),the result in the end is 6174,the Comgrich Content.*");
	puts("**************************************************************");
	while (n != 0)
	{
		printf(" >> Please input a 4-digit number to verify(0 to quit): ");
		scanf("%d", &n);      /*输入任一整数*/
		if (n == 0)
			break;
		printf(" >> ------ Results of verification: ------------\n");
		count = 0;
		vr6174(n);           /*调用函数进行验证*/
		printf(" >> ---------------------------------------------\n");
	}
	system("pause");
}
void vr6174(int num)
{
	int each[4], max, min;
	if (num != 6174 && num)    /*若不等于74且不等于0则进行卡布列克运算*/
	{
		parse_sort(num, each);         /*将整数分解,数字存入each数组中*/
		max_min(each, &max, &min);      /*求数字组成的最大值和最小值*/
		num = max - min;          /*求最大值和最小值的差*/
		printf(" >> Step No.%d:  %d-%d=%d\n", ++count, max, min, num); /*输出该步计算过程*/
		vr6174(num);         /*递归调用自身继续进行卡布列克运算*/
	}
}
void parse_sort(int num, int *each)
{
	int i, *j, *k, temp;
	for (i = 0; i <= 4; i++)         /*将NUM分解为数字*/
	{
		j = each + 3 - i;
		*j = num % 10;
		num /= 10;
	}
	for (i = 0; i<3; i++)     /*对各保数字从小到大进行排序*/
	for (j = each, k = each + 1; j<each + 3 - i; j++, k++)
	if (*j>*k) { temp = *j; *j = *k; *k = temp; }
	return;
}
void max_min(int *each, int *max, int *min)    /*将分解的数字还原为最大整数和最小整数*/
{
	int *i;
	*min = 0;
	for (i = each; i<each + 4; i++)     /*还原为最小的整数*/
		*min = *min * 10 + *i;
	*max = 0;
	for (i = each + 3; i >= each; i--)    /*还原为最大的整数*/
		*max = *max * 10 + *i;
	return;
}

97、尼科彻斯定理

#include<stdio.h>
#include<stdlib.h>

void vrNico(int a)
{
	int b, c, d;
	b = a*a*a;                  /*求整数的三次方*/
	printf(" >> %d*%d*%d=%d=", a, a, a, b);
	for (d = 0, c = 0; c<a; c++)       /*输出数列,首项为a*a-a+1,等差值为2*/
	{
		d += a*a - a + 1 + c * 2;       /*求数列的前a项的和*/
		printf(c ? "+%d" : "%d", a*a - a + 1 + c * 2);
	}
	if (d == b)printf(" Satisfy!\n");    /*若条件满足则输出"Y"*/
	else printf(" Dissatisfy!\n");       /*否则输出"N"*/
}


void main()
{

	int n = 1;
	puts("******************************************************");
	puts("*    This program is to verify Theorem of Nicoqish.  *");
	puts("* That is the cube of any integer can be represented *");
	puts("* as the sum of some continue odd numbers.           *");
	puts("* For example, 8^3=512=57+58+59+61+63+65+67+69+71.   *");
	puts("******************************************************");
	while (n != 0)
	{
		printf(" >> Please input a integer to verify(0 to quit): ");
		scanf("%d", &n);      /*输入任一整数*/
		if (n == 0)
			break;
		printf(" >> ------ Results of verification: ------------\n");
		vrNico(n);           /*调用函数进行验证*/
		printf(" >> ---------------------------------------------\n");
	}
	system("pause");
}

98、扑克牌自动发牌

#include<stdlib.h>
#include<stdio.h>

int comp(const void *j, const void *i);
void p(int p, int b[], char n[]);

void main()
{
	static char n[] = { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' };
	int a[53], b1[13], b2[13], b3[13], b4[13];
	int b11 = 0, b22 = 0, b33 = 0, b44 = 0, t = 1, m, flag, i;
	puts("******************************************************");
	puts("*      This is an Automatic Dealing Card program!    *");
	puts("*  In one game, 52 cards are divided into 4 groups.  *");
	puts("******************************************************");
	printf(" >> ----- Each person's cards are as follows. -------");
	while (t <= 52)					/* 控制发52张牌 */
	{
		m = (rand() % 5) + 1;       /* 产生0到51之间的随机数 */
		for (flag = 1, i = 1; i <= t&&flag; i++)   /* 查找新产生的随机数是否已经存在 */
		if (m == a[i]) flag = 0;      /* flag=1:产生的是新的随机数
										 flag=0:新产生的随机数已经存在 */
		/* 如果产生了新的随机数,则存入数组 */
		if (flag)
		{
			a[t++] = m;       
			if (t % 4 == 0) b1[b11++] = a[t - 1];        /* 根据t的模值,判断当前 */
			else if (t % 4 == 1) b2[b22++] = a[t - 1];   /* 的牌应存入哪个数组中 */
			else if (t % 4 == 2) b3[b33++] = a[t - 1];
			else if (t % 4 == 3) b4[b44++] = a[t - 1];
		}
	}
	/* 将每个人的牌进行排序 */
	qsort(b1, 13, sizeof(int), comp);      
	qsort(b2, 13, sizeof(int), comp);
	qsort(b3, 13, sizeof(int), comp);
	qsort(b4, 13, sizeof(int), comp);
	p(1, b1, n); p(2, b2, n); p(3, b3, n); p(4, b4, n);     /* 分别打印每个人的牌 */
	system("pause");
}

void p(int p, int b[], char n[])
{
	int i;
	printf("\n   Person No.%d   \006 ", p);			/* 打印黑桃标记 */
	for (i = 0; i<13; i++)							/* 将数组中的值转换为相应的花色 */
	if (b[i] / 13 == 0) printf(" %c", n[b[i] % 13]);      /* 该花色对应的牌 */
	printf("\n                 \003 ");				/* 打印红桃标记 */
	for (i = 0; i<13; i++)
	if ((b[i] / 13) == 1) printf(" %c", n[b[i] % 13]);
	printf("\n                 \004 ");				/* 打印方块标记 */
	for (i = 0; i<13; i++)
	if (b[i] / 13 == 2) printf(" %c", n[b[i] % 13]);
	printf("\n                 \005 ");				/* 打印梅花标记 */
	for (i = 0; i<13; i++)
	if (b[i] / 13 == 3 || b[i] / 13 == 4) printf(" %c", n[b[i] % 13]);
	printf("\n");
}

/* qsort调用的排序函数 */
int comp(const void *j, const void *i) { return(*(int*)i - *(int*)j); }

99、常胜将军

#include<stdio.h>
#include<stdlib.h>

void main()
{
	int a = 21, i;
	puts("*****************************************************");
	puts("*            This is a Matchstick Taken Game.       *");
	puts("* There are 21 machsticks, two persons take them in *");
	puts("* turn. Each one each time takes 1 to 4 sticks. The *");
	puts("* one who takes the last stick will lose the game.  *");
	puts("*****************************************************");
	printf(" >> --------------- Game Begin ---------------------\n");
	while (a>0)
	{
		do{
			printf(" >> How many sticks do you wish to take(1~%d)?", a>4 ? 4 : a);
			scanf("%d", &i);
		} while (i>4 || i<1 || i>a);      /* 接收正在确的输入 */
		if (a - i>0) printf(" >> %d stick left in the pile.\n", a - i);
		if ((a - i) <= 0)
		{
			printf(" >> You have taken the last stick.\n");
			printf(" >> ******* You lose! ******* \n");			/* 输出取胜标记 */
			printf(" >> --------------- Game Over! ---------------------\n");
			break;
		}
		else
			printf(" >> Compute take %d stick.\n", 5 - i);		/* 输出计算机取的子数 */
		a -= 5;
		printf(" >> %d stick left in the pile.\n", a);
	}
	system("pause");
}

100、搬山游戏

#include<stdio.h>
#include<stdlib.h>

void main()
{
	int n, k, x, y, cc, pc, g;
	puts("*******************************************************");
	puts("*            This is a Mountain Moveing Game.         *");
	puts("* There are n mountains, two persons move them in     *");
	puts("* turn. Each one each time moves 1 to k mountains, the*");
	puts("* one who takes the last stick will lose the game.    *");
	puts("*******************************************************");
	printf(" >> --------------- Game Begin ---------------------\n");
	pc = cc = 0;
	g = 1;
	for (;;)
	{
		printf(" >> No.%2d game \n", g++);
		printf(" >> ---------------------------------------\n");
		printf(" >> How many mountains are there? ");
		scanf("%d", &n);
		if (!n) break;
		printf(" >> How many mountains are allowed to each time? ");
		do{
			scanf("%d", &k);
			if (k>n || k<1) printf(" >> Repeat again!\n");
		} while (k>n || k<1);
		do{
			printf(" >> How many mountains do you wish move ? ");
			scanf("%d", &x);
			if (x<1 || x>k || x>n)      /* 判断搬山数是否符合要求 */
			{
				printf(" >> Illegal,again please!\n");
				continue;
			}
			n -= x;
			printf(" >> There are %d mountains left now.\n", n);
			if (!n)
			{
				printf(" >> ---- I win. You are failure.----------\n\n"); cc++;
			}
			else
			{
				y = (n - 1) % (k + 1);      /*求出最佳搬山数*/
				if (!y) y = 1;
				n -= y;
				printf(" >> Copmputer move %d mountains away.\n", y);
				if (n) printf(" >> There are %d mountains left now.\n", n);
				else
				{
					printf(" >> ---- I am failure. You win.-----------\n\n");
					pc++;
				}
			}
		} while (n);

	}
	printf(" >> Games in total have been played %d.\n", cc + pc);
	printf(" >> You score is win %d,lose %d.\n", pc, cc);
	printf(" >> My score is win %d,lose %d.\n", cc, pc);
	printf(" >> --------------- Game Over! ---------------------\n");
	system("pause");
}

101、兔子产子(斐波那契数列)

#include<stdio.h>
#include<stdlib.h>

void main()
{
	int n, i, j, un1, un2, un;
	puts("********************************************************");
	puts("*   This is a program to Calculate Rabbits Numbers.    *");
	puts("* There is a rabbit couple procreats 2 rabbits 1 month,*");
	puts("* and the young rabbits group and can procreats in the *");
	puts("* end of the second month. In this way,how many rabbits*");
	puts("* are there after n generations?                       *");
	puts("********************************************************");
	for (n = 2; n<3;)
	{
		printf(" >> Please input number of generations (n>2): ");
		scanf("%d", &n);
		if (n<3) printf("\n >> Input error!\n");     /* 控制输入正确的N值 */
	}
	un = un2 = 1;
	printf(" >> The numbers of rabbits in first %d generation are as follows:\n", n);
	printf(" l\t l\t");

	for (i = 3, j = 0; i <= n; i++)
	{
		un1 = un2;
		un2 = un;
		un = un1 + un2;							/* 利用通项公式求解N项的值 */
		printf(i % 8 ? " %d\t" : "%d\n", un);
	}
	printf("\n");
	system("pause");
}

102、数字移动

#include<stdio.h>
#include<stdlib.h>

int a[] = { 0, 1, 2, 5, 8, 7, 6, 3 };   /* 指针数组.依次存入矩阵中构成环的元素下标 */
int b[9];								/* 表示3X3矩阵,b[4]为空格 */
int c[9];								/* 确定1所在的位置后,对环进行调整的指针数组 */
int count = 0;							/* 数字移动步数计数器 */

void main()
{
	int i, j, k, t;
	void print();
	puts("*****************************************************");
	puts("*         This is a program to Move Numbers.        *");
	puts("*****************************************************");
	printf(" >> Please enter original order of digits 1~8: ");
	for (i = 0; i<8; i++)
		scanf("%d", &b[a[i]]);
	/* 顺序输入矩阵外边的8个数字,矩阵元素的顺序由指针数组的元素a[i]控制 */
	printf("The sorting process is as felow:\n");
	print();
	for (t = -1, j = 0; j<8 && t == -1; j++)			/* 确定数字1所在的位置 */
	if (b[a[j]] == 1) t = j;							/* t:记录数字1所在的位置 */
	/* 调整环的指针数组,将数字1所在的位置定为环的首 */
	for (j = 0; j<8; j++)								
		c[j] = a[(j + t) % 8];
	/* 从2开始依次调整数字的位置 */
	for (i = 2; i<9; i++)         
		/* i:正在处理的数字,i对应在环中应当的正确位置就是i-1 */
		for (j = i - 1; j<8; j++)     
			/* 从i应处的正确位置开始顺序查找 */
			if (b[c[j]] == i&&j != i - 1)      /* 若i不在正确的位置 */
			{
				b[4] = i;					/* 将i移到中心的空格中 */
				b[c[j]] = 0; print();		/* 空出i原来所在的位置,输出 */
				for (k = j; k != i - 1; k--)    /* 将空格以前到i的正确位置之间的数字依次向后移动一格 */
				{
					b[c[k]] = b[c[k - 1]];		/* 数字向后移动 */
					b[c[k - 1]] = 0;
					print();
				}
				b[c[k]] = i;         /* 将中间的数字i移入正确的位置 */
				b[4] = 0;            /* 空出中间的空格 */
				print();
				break;
			}
	else if (b[c[j]] == i) break;       /* 数字i在正确的位置 */
	system("pause");
}

/* 按格式要求输出矩阵 */
void print(void)        
{
	int c;
	printf(" >> Step No.%2d  ", count++);
	for (c = 0; c<9; c++)
	if (c % 3 == 2) printf("%2d  ", b[c]);
	else  printf("%2d", b[c]);
	printf("\n");
}

103、多项式乘法

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define MAX 50
/* 下面的两个数组可以根据具体要求解的多项式来决定其值 */
static double p[6] = { 4, -6, 3, 1, -1, 5 };	/* 表示多项式4x^5 - 6x^4 + 3x^3 + x^2 - x + 5 */
static double q[4] = { 3, 2, -5, 1 };			/* 表示多项式3x^3 + 2x^2 - 5x + 1 */
static double result[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };		/* 存放乘积多项式 */

void npmul(double p[], int m, double q[], int n, double s[])
{
	int i, j;
	for (i = 0; i <= m - 1; i++)
	for (j = 0; j <= n - 1; j++)
		s[i + j] = s[i + j] + p[i] * q[j];		/* 迭带计算各项系数 */
	return;
}

/* 计算所给多项式的值 */
double compute(double s[], int k, float x)					
{
	int i;
	float multip = 1;
	double sum = 0;
	for (i = 0; i<k; i++) 
		multip = multip * x;			/* 先求出x的最高次项的值 */
	for (i = k - 1; i >= 0; i--)
	{
		sum = sum + s[i] * multip;		/* 依次从高到低求出相对应次项的值 */
		if (x != 0)
			multip = multip / x;
	}
	return sum;
}

void main()
{
	int i, j, m, n;
	double  px[MAX], qx[MAX], rx[MAX];
	float x;
	for (i = 0; i<MAX; i++)
		rx[i] = 0;
	puts("      This is a polynomial multiplication program.");
	puts("It calculate the product of two polynomials: P(x) and Q(x)");
	puts("       P(x)=Pm-1*x^(m-1)+Pm-2*x^(m-2)+...+P1*x+P0");
	puts("       Q(x)=Qn-1*x^(n-1)+Qn-2*x^(n-2)+...+Q1*x+Q0");
	printf("\n >> Please input m (>=1): ");
	scanf("%d", &m);
	printf(" >> Please input P%d, P%d, ... P1, P0 one by one:\n", m - 1, m - 2);
	for (i = 0; i<m; i++)
		scanf("%f", &px[i]);
	printf("\n >> Please input n (>=1): ");
	scanf("%d", &n);
	printf(" >> Please input Q%d, Q%d, ... Q1, Q0 one by one:\n", n - 1, n - 2);
	for (i = 0; i<n; i++)
		scanf("%f", &qx[i]);
	npmul(p, m, q, n, rx);
	printf("\nThe product of two polynomials R(x) is :\n");
	for (i = m + n - 1, j = 0; i >= 1; i--)					/*逐行逐项打印出结果多项式*/
	{
		printf(" (%f*x^%d) + ", rx[m + n - 1 - i], i - 1);
		if (j == 2)
		{
			printf("\n");
			j = 0;
		}
		else
			j++;
	}
	printf("\n");
	printf("Input the value of x: ");
	scanf("%f", &x);
	printf("\nThe value of the R(%f) is: %13.7f", x, compute(rx, m + n - 1, x));
	system("pause");
}

104、产生随机数

#include <stdio.h>
#include <sys\timeb.h>
#include <stdlib.h>
#define Alpha 3.90

double initvalue();

/** 返回一个(0,1)之间的随机数 */
double random(void)
{
	static double f = -1.0;
	double initvlaue();
	if (f == -1.0) f = initvalue();
	else f = Alpha*f*(1.0 - f);
	return f;
}

/* 返回随机数序列初值 */
double initvalue()
{
	double f0;
	struct timeb *pr;
	while (1)
	{
		ftime(pr);
		f0 = pr->millitm*0.9876543*0.001;
		if (f0<0.001) continue;
		break;
	}
	return f0;
}

void main()
{
	double test;
	int i;
	puts("This is a random number generator.");
	puts("\n The random number are: ");
	for (i = 0; i < 3; i++)
	{
		test = random();
		printf(" >> rand%d:%f\n", i, test);
	}
	system("pause");
}

105、堆栈四则运算

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>

#define TRUE 1
#define FALSE 0
#define STACK_INIT_SIZE 100	/* 存储空间初始分配量 */
#define STACKINCREMENT 20	/* 存储空间分配增量 */

typedef struct
{
	int *pBase;		/* 在构造之前和销毁之后,base的值为NULL */
	int *pTop;		/* 栈顶指针 */
	int StackSize;	/* 当前已分配的存储空间,以元素为单位 */
}Stack;

typedef int BOOLEAN;

char Operator[8] = "+-*/()#";	/* 合法的操作符存储在字符串中 */
char Optr;						/* 操作符 */
int Opnd = -1;					/* 操作符 */
int Result;						/* 操作结果 */

/* 算符间的优先关系 */
char PriorityTable[7][7] =
{
	{ '>', '>', '<', '<', '<', '>', '>' },
	{ '>', '>', '<', '<', '<', '>', '>' },
	{ '>', '>', '>', '>', '<', '>', '>' },
	{ '>', '>', '>', '>', '<', '>', '>' },
	{ '<', '<', '<', '<', '<', '=', 'o' },
	{ '>', '>', '>', '>', 'o', '>', '>' },
	{ '<', '<', '<', '<', '<', 'o', '=' },
};

//数据对象的操作方法
//构造一个空栈,如果返回值为0,则表示初始化失败
Stack InitStack()
{
	Stack S;
	S.pBase = (int*)malloc(STACK_INIT_SIZE*sizeof(int));
	if (!S.pBase)
	{
		printf("内存分配失败,程序中止运行\n");
		exit(-1);
	}
	else
	{
		S.pTop = S.pBase;
		S.StackSize = STACK_INIT_SIZE;
	}
	return S;
}

/* 销毁栈S,S不再存在 */
void DestoryStack(Stack *S)
{
	if (S->pBase)
	{
		free(S->pBase);
		S->pTop = S->pBase = NULL;

	}
}

//若栈不空,则用e返回S的栈顶元素
//注:由于应用的特殊,可以不检查栈是否为空
int GetTop(Stack S)
{
	return *(S.pTop - 1);
}

/** 插入元素e为新的栈顶元素,如果成功则返回1,否则返回0 */
int Push(Stack *S, int e)
{
	if (S->pTop - S->pBase == S->StackSize)
	{//栈满,追加存储空间
		S->pBase = (int*)realloc(S->pBase, S->StackSize + STACKINCREMENT*sizeof(int));
		if (!S->pBase)
			return 0;//存储分配失败
		S->pTop = S->pBase + S->StackSize;
		S->StackSize += STACKINCREMENT;
	}
	*(S->pTop++) = e;
	return 1;
}

int Pop(Stack *S, int *e)
{
	//若栈不空,则删除S的栈顶元素,用e 返回其值,并返回1;否则返回0
	if (S->pTop == S->pBase)
		return 0;
	*e = *--(S->pTop);
	return 1;

}

// 主函数及其它函数的实现
// 比较两个数学符号operator_1,operator_2的计算优先权,在算符优先关系表中查找相应的关系并返回'<','=',或'>'
char CheckPriority(char operator_1, char operator_2)
{
	int i, j;// 用来查询算符间优先关系表的下标
	//char *ptr;
	i = strchr(Operator, operator_1) - Operator;// 找到传入操作符在字符串Operators中的相对位置
	j = strchr(Operator, operator_2) - Operator;
	// 返回算符优先关系表中相应值
	return PriorityTable[i][j];
}

BOOLEAN IsOperator(char ch)
{
	// 判断一个字符是否为打操作符
	if (strchr(Operator, ch))
		return TRUE;
	else
		return FALSE;

}

// 从键盘获得输入
void GetInput(void)
{
	char Buffer[20];	// 键盘输入缓冲区,用来处理输入多位数的情况
	char ch;			// 存放键盘输入
	int index;			// 存放Buffer的下标
	index = 0;
	ch = getch();		//	从键盘读入一个字符
	while (ch != 13 && !IsOperator(ch))
	{//	如果输入的字符是回车符或是操作符,循环结束
		if (ch >= '0'&&ch <= '9')
		{// 将字符回显到屏幕
			printf("%c", ch);
			Buffer[index] = ch;
			index++;

		}
		ch = getch();
	}
	if (ch == 13)
		Optr = '#';// 输入的表达式以回车符结束
	else
	{
		Optr = ch;
		printf("%c", ch);

	}
	if (index>0)
	{
		Buffer[index] = '\0';
		Opnd = atoi((Buffer));
	}
	else
		Opnd = -1;// 程序不支持输入负数,当Opnd为负数时,表示输入的字符为操作符
}

/** 计算形如a+b之类的表达式,theta为操作符,a,b为操作数 */ 
int Calc(int a, char theta, int b)
{
	switch (theta)
	{
	case '+':
		return a + b;
	case '-':
		return a - b;
	case '*':
		return a*b;
	default:
		if (b == 0)	// 除数为零的情况
		{
			printf("除数不能为");
			return 0;// 返回0用以显示
		}
		else
			return a / b;
	}
}
/* 表达式求值 */
BOOLEAN EvaluateExpression()
{
	int temp;		// 临时变量
	char theta;		// 存放操作符的变量
	int itheta;		// 存放出栈的操作符的变量add by me
	int a, b;		// 存放表达式运算时的中间值
	int topOpnd;	// 栈顶操作数
	char topOptr;	// 栈顶操作符

	Stack OPTR = InitStack();// 操作符栈
	Stack OPND = InitStack();// 操作数栈

	if (!Push(&OPTR, '#'))// 操作符栈中的第一个为#字符
		return FALSE;

	GetInput();// 从键盘获得输入

	while (Optr != '#' || GetTop(OPTR) != '#')
	{// 如果Optr>=0,表示有操作数输入
		if (Opnd >= 0)Push(&OPND, Opnd);
		switch (CheckPriority(GetTop(OPTR), Optr))
		{
		case '<':// 栈顶元素优先权低
			if (!Push(&OPTR, Optr))return FALSE;
			GetInput();
			break;
		case '=':// 脱括号并接收键盘输入
			Pop(&OPTR, &temp); GetInput();
			break;
		case '>':// 退栈并将运算结果入栈
			// 先用itheta得到操作符在赋给theta
			Pop(&OPTR, &itheta);
			Pop(&OPND, &b);
			Pop(&OPND, &a);
			theta = (char)(itheta);
			Push(&OPND, Calc(a, itheta, b));
			Opnd = -1;
			break;

		}
	}
	//本算法中,当输入只有一个操作数然后就输入回车符时,
	//OPND.pTop==OPND.pBase
	//如果OPND.pTop==OPND.pBase并且Opnd<0,则说明用户
	//未输入任何操作和操作符而直接输入[回车],程序直接
	//退出运行
	if (OPND.pTop == OPND.pBase&&Opnd<0)
	{
		printf("\n\n感谢使用!\n");
		exit(1);

	}
	else if (OPND.pTop == OPND.pBase)
		Result = Opnd;
	else
	{
		Result = GetTop(OPND);
		DestoryStack(&OPND);
		DestoryStack(&OPTR);
	}
	return TRUE;

}

void Message(void)
{
	printf("\n四则运算表达式求值演示\n");
	printf("-------------------------------\n");
	printf("使用方法:请从键盘上直接输入表达式,以回车键结束.如45*(12-2)[回车]\n");
	printf("注0:不输入任何数而直接按[回车]键,将退出程序.\n");
	printf("注1:本程序暂时不接受除数字键及四则运算符之外的任何其它键盘输入.\n");
	printf("注2:本程序暂时只能处理正确的表达式,不支持输入负数.\n");
	printf("-------------------------------\n\n");
}
void main(void)
{
	int i;	// 用来一些说明性信息
	Message();
	for (i = 1;; i++)
	{
		printf("表达式%d:", i);
		if (EvaluateExpression())
			printf("=%d\n", Result);
		else
			printf("计算中遇到错误\n");
	}
	system("pause");
}

106、递归整数四则运算

/*
对四则混合运算所提取的形式化表达式(生成式)
<exp> -> <term> { <addop> <term> }
<addop> -> + | -
<term> -> <factor> { <mulop> <factor> }
<mulop> -> * | /
<factor> -> ( <exp> ) | Number
*/

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

char token; /* 全局标志变量 */

/* 递归调用的函数原型 */
int exp(void);
int term(void);
int factor(void);

/* 报告出错信息的函数 */
void error(void) 
{
	fprintf(stderr, "错误\n");
	exit(1);
}

/* 对当前的标志进行匹配 */
void match(char expectedToken) 
{
	if (token == expectedToken) token = getchar(); /* 匹配成功,获取下一个标志 */
	else error();				/* 匹配不成功,报告错误 */
}

void Message(void)
{
	printf("================================================================\n");
	printf("*               递归实现的四则运算表达式求值程序               *\n");
	printf("****************************************************************\n");
	printf("使用方法:请从键盘上直接输入表达式,以回车键结束.如45*(12-2)[回车]\n");
	printf("*****************************************************************\n\n");
}

void main()
{
	int result;  /* 运算的结果 */
	Message();
	printf(" >> 请输入表达式: ");
	token = getchar();		/* 载入第一个符号 */

	result = exp();			/*进行计算*/
	if (token == '\n')		/* 是否一行结束 */
		printf(" >> 表达式的计算结果为 : %d\n", result);
	else error();			/* 出现了例外的字符 */
	system("pause");
}

int exp(void)
{
	int temp = term();			/* 计算比加减运算优先级别高的部分 */
	while ((token == '+') || (token == '-'))
		switch (token) {
		case '+': match('+');    /*加法*/
			temp += term();
			break;
		case '-': match('-');
			temp -= term();		 /*减法*/
			break;
	}
	return temp;
}

int term(void)
{
	int div; /*除数*/
	int temp = factor();   /*计算比乘除运算优先级别高的部分*/
	while ((token == '*') || (token == '/'))
		switch (token) {
		case '*': match('*');  /*乘法*/
			temp *= factor();
			break;
		case '/': match('/');   /*除法*/
			div = factor();
			if (div == 0) /*需要判断除数是否为0*/
			{
				fprintf(stderr, "除数为0.\n");
				exit(1);
			}
			temp /= div;
			break;
	}
	return temp;
}

int factor(void)
{
	int temp;
	if (token == '(') /*带有括号的运算*/
	{
		match('(');
		temp = exp();
		match(')');
	}
	else if (isdigit(token)) /*实际的数字*/
	{
		ungetc(token, stdin); /*将读入的字符退还给输入流*/
		scanf("%d", &temp); /*读出数字*/
		token = getchar();  /*读出当前的标志*/
	}
	else error(); /*不是括号也不是数字*/
	return temp;
}

107、复平面作图

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>


void oplot(int n, double x[], double y[]) /*作图函数,这里使用DOS的文本模式画图*/
{
	int i, j;
	char screen[25][80]; /*声明一个字符型数组,用来表示屏幕的输出*/
	memset(screen, ' ', 25 * 80);  /*将数组整体赋值为空格*/
	/*画x轴*/
	for (i = 0; i <79; i++)
		screen[10][i] = '-';
	screen[10][79] = 'X';
	/*画y轴*/
	for (i = 1; i <25; i++)
		screen[i][40] = '|';
	screen[0][40] = 'Y';
	/*将符合条件的点(x,y)赋值成星号*/
	for (i = 0; i < n; i++)
		screen[(int)(x[i] + 10)][(int)(y[i] * 2 + 40)] = '*';
	/*输出数组,在屏幕上画图*/
	for (i = 0; i < 25; i++)
	for (j = 0; j <80; j++)
		printf("%c", screen[i][j]);
}

void main()
{
	int points, k;
	double x[50], y[50], angle, portion;

	points = 40; /*一共画40个点*/
	portion = 4.0 * 360 / points; /*将720度分成40份。*/
	/*下边是求点的计算*/
	for (k = 0; k<points; k++)
	{
		angle = k * portion; /*求出角度*/
		x[k] = 2.0 + angle*cos(angle); /*x,也就是复数的实部*/
		y[k] = angle*sin(angle); /*y,即复数的虚部*/
	}
	oplot(points, x, y); /*对所求出的点作图*/

	system("pause");
}

108、绘制彩色抛物线

#include <graphics.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/*画抛物线的子函数spara()*/
/*row,col代表抛物线顶点的坐标,x1,y1是抛物线起点相对顶点的坐标*/
/*t为抛物线绕顶点旋转的角度*/
void spara(int row, int col, int x1, int y1, int t, int color)
{
	int n, dx, dy, x, y, x2, y2;
	double ct, st;
	double f, fx, fy, b, a, rx;
	st = (double)t*3.1415926 / 180.0;		/*把角度转化为弧度*/
	ct = cos(st); st = sin(st);
	n = abs(x1) + abs(y1); n = n + n;
	dx = 1; dy = 1; f = 0.0;				/*初始化工作*/
	if (x1>0) dx = -1;
	if (y1>0) dy = -1;
	a = y1; b = x1; b = b*b;
	rx = -a - a; fx = 2.0*x1*dx + 1.0;
	fx = -a*fx; fy = b;
	if (dy<0) fy = -fy;
	x = x1; y = y1;
	x2 = (double)x*ct - (double)y*st + 2000.5;
	y2 = (double)x*st + (double)y*ct + 2000.5;
	x2 = x2 - 2000; y2 = y2 - 2000;
	putpixel(row - y2, col + x2, color);
	while (n>0)						/*具体的运算法则见上面的公式*/
	{
		n = n - 1;
		if (f >= 0.0)
		{
			x = x + dx;
			x2 = (double)x*ct - (double)y*st + 2000.5;
			y2 = (double)x*st + (double)y*ct + 2000.5;
			x2 = x2 - 2000; y2 = y2 - 2000;
			putpixel(row - y2, col + x2, color);
			if (fx>0.0) f = f - fx;
			else f = f + fx;
			fx = fx + rx;
			if (fx == 0.0 || (fx<0.0&&fx - rx>0.0) || (fx>0.0&&fx - rx<0.0))
			{
				dy = -dy; fy = -fy; f = -f;
			}
		}
		else
		{
			y = y + dy;
			x2 = (double)x*ct - (double)y*st + 2000.5;
			y2 = (double)x*st + (double)y*ct + 2000.5;
			x2 = x2 - 2000; y2 = y2 - 2000;
			putpixel(row - y2, col + x2, color);
			if (fy>0.0) f = f + fy;
			else f = f - fy;
		}
	}
	return;
}

void main()
{
	int i, color;
	int gdriver = DETECT, gmode;
	color = 1;
	registerbgidriver(EGAVGA_driver);
	initgraph(&gdriver, &gmode, "..\\bgi");			/*初始化图形界面*/
	for (i = 1; i <= 4; i++)							/*先画出四个互成90度的抛物线*/
	{
		spara(200, 200, 100, 100, i * 90, color);
		color += 3;
		getch();
	}
	color = 1;
	for (i = 1; i <= 11; i++)							/*再画12个互成30度的抛物线*/
	{
		spara(200, 200, 100, 100, i * 30, color);
		color++;
	}
	getch();
	closegraph();
	system("pause");
}

109、绘制正态分布曲线

#include <stdio.h>
#include <math.h>
#include <graphics.h>

double lgam1(double x) /*Gamma函数的计算*/
{
	int i;
	double y, t, s, u;
	static double a[11] = { 0.0000677106, -0.0003442342,
		0.0015397681, -0.0024467480, 0.0109736958,
		-0.0002109075, 0.0742379071, 0.0815782188,
		0.4118402518, 0.4227843370, 1.0 };
	if (x <= 0.0)
	{
		printf("err**x<=0!\n"); return(-1.0);
	}
	y = x;
	if (y <= 1.0)
	{
		t = 1.0 / (y*(y + 1.0)); y = y + 2.0;
	}
	else if (y <= 2.0)
	{
		t = 1.0 / y; y = y + 1.0;
	}
	else if (y <= 3.0) t = 1.0;
	else
	{
		t = 1.0;
		while (y>3.0)
		{
			y = y - 1.0; t = t*y;
		}
	}
	s = a[0]; u = y - 2.0;
	for (i = 1; i <= 10; i++)
		s = s*u + a[i];
	s = s*t;
	return(s);
}
double lgam2(double a, double x) /*不完全Gamma函数*/
{
	int n;
	double p, q, d, s, s1, p0, q0, p1, q1, qq;
	if ((a <= 0.0) || (x<0.0))
	{
		if (a <= 0.0) printf("err**a<=0!\n");
		if (x<0.0) printf("err**x<0!\n");
		return(-1.0);
	}
	if (x + 1.0 == 1.0) return(0.0);
	if (x>1.0e+35) return(1.0);
	q = log(x); q = a*q; qq = exp(q);
	if (x<1.0 + a)
	{
		p = a; d = 1.0 / a; s = d;
		for (n = 1; n <= 100; n++)
		{
			p = 1.0 + p; d = d*x / p; s = s + d;
			if (fabs(d)<fabs(s)*1.0e-07)
			{
				s = s*exp(-x)*qq / lgam1(a);
				return(s);
			}
		}
	}
	else
	{
		s = 1.0 / x; p0 = 0.0; p1 = 1.0; q0 = 1.0; q1 = x;
		for (n = 1; n <= 100; n++)
		{
			p0 = p1 + (n - a)*p0; q0 = q1 + (n - a)*q0;
			p = x*p0 + n*p1; q = x*q0 + n*q1;
			if (fabs(q) + 1.0 != 1.0)
			{
				s1 = p / q; p1 = p; q1 = q;
				if (fabs((s1 - s) / s1)<1.0e-07)
				{
					s = s1*exp(-x)*qq / lgam1(a);
					return(1.0 - s);
				}
				s = s1;
			}
			p1 = p; q1 = q;
		}
	}
	printf("a too large !\n");
	s = 1.0 - s*exp(-x)*qq / lgam1(a);
	return(s);
}

double lerrf(double x) /*误差函数*/
{
	double y;
	if (x >= 0.0)
		y = lgam2(0.5, x*x);
	else
		y = -lgam2(0.5, x*x);
	return(y);
}
double lgass(double a, double d, double x) /*正态分布函数*/
{
	double y;
	if (d <= 0.0) d = 1.0e-10;
	y = 0.5 + 0.5*lerrf((x - a) / (sqrt(2.0)*d));
	return(y);
}

void main()
{
	int i;
	double j;
	double a, d;

	int gdriver = DETECT, gmode;
	printf("This program will draw the Normal Distribution Graph.\n");
	printf("Please input the mathematical expectation (Alpha): ");
	scanf("%lf", &a);
	printf("Please input the variance (Sita >0): ");
	scanf("%lf", &d);
	/*registerbgidriver( EGAVGA_driver );*/
	initgraph(&gdriver, &gmode, "e:\\tc\\bgi");

	setbkcolor(BLUE);
	moveto(50, 430);
	lineto(590, 430);
	outtextxy(600, 425, "X");
	moveto(200, 50);
	lineto(200, 450);
	outtextxy(200, 30, "Y");
	outtextxy(185, 435, "O");

	setcolor(RED);
	moveto(51, 430 - 100 * lgass(a, d, -150.0));
	for (i = 51; i <= 590; i++)
	{
		j = 430 - 360 * lgass(a, d, (double)(i - 200));
		lineto(i, j);
	}
	getch();
	closegraph();

	system("pause");
}

110、求解非线性方程

#include <math.h>
#include <stdio.h>
#include <stdlib.h>


int BinSearchRoot(double a, double b, double h, double eps, double x[], int m) /*用二法计算非线性方程的实根*/
/*参数意义:
a    要求的根的下界
b    要求的根的上界,即:所求的根落在区间 [a,b]之内
h    递进的步长
eps  精度
x    根的值
m    预计的根的个数*/
{
	extern double Equation(double x); /*要求解的非线性方程*/
	int n, js;
	double z, y, z1, y1, z0, y0;
	n = 0; z = a; y = Equation(z);
	while ((z <= b + h / 2.0) && (n != m)) /*对给定步长的子区间进行搜索*/
	{
		if (fabs(y)<eps)  /*当前的判定点是方程的根*/
		{
			n = n + 1;
			x[n - 1] = z;
			z = z + h / 2.0;
			y = Equation(z);
		}
		else /*当前点不是方程的根*/
		{
			z1 = z + h;
			y1 = Equation(z1);
			if (fabs(y1)<eps) /*下一个点是方程的根*/
			{
				n = n + 1;
				x[n - 1] = z1;
				z = z1 + h / 2.0;
				y = Equation(z);
			}
			else if (y*y1>0.0) /*该区间内无根*/
			{
				y = y1; z = z1;
			}
			else   /*该区间内有根*/
			{
				js = 0;/*标志,0表示未找到根,1表示已经确定了根*/
				while (js == 0)
				{
					if (fabs(z1 - z)<eps) /*区间的长度小于给定的精度,可以当作已经找到了根*/
					{
						n = n + 1;
						x[n - 1] = (z1 + z) / 2.0; /*把区间的中位值作为根*/
						z = z1 + h / 2.0; /*把寻找的位置放到下一个区间内*/
						y = Equation(z);
						js = 1; /*在当前区间内已经找到了根*/
					}
					else /*区间比给定的精度大,则进行二分*/
					{
						z0 = (z1 + z) / 2.0;  /*区间二分*/
						y0 = Equation(z0);
						if (fabs(y0)<eps) /*z0位置为根*/
						{
							x[n] = z0;
							n = n + 1;
							js = 1;
							z = z0 + h / 2.0;
							y = Equation(z);
						}
						else if ((y*y0)<0.0) /*[z,z0]内有根*/
						{
							z1 = z0; y1 = y0;
						}
						else { z = z0; y = y0; }
					}
				}
			}
		}
	}
	return(n); /*返回根的个数*/
}

void main()
{
	int i, n;
	static int m = 6;
	static double x[6];

	puts("This is a program to solve Nonlinear function\n   by Binary Divisive Procedure.");
	puts("\n The Nonlinear function is:");
	puts("\n f(x)=(((((x-5.0)*x+3.0)*x+1.0)*x-7.0)*x+7.0)*x-20.0\n");
	n = BinSearchRoot(-2.0, 5.0, 0.2, 0.000001, x, m);
	puts("\n >> Solve successfully!\n >> The results are:");
	printf(" >> The function has %d roots, they are:\n", n);/*输出根的个数*/
	for (i = 0; i <= n - 1; i++)
		printf(" >> x(%d)=%13.7e\n", i, x[i]);
	system("pause");
}

double Equation(double x)
{
	double z;
	z = (((((x - 5.0)*x + 3.0)*x + 1.0)*x - 7.0)*x + 7.0)*x - 20.0;
	return(z);
}

111、实矩阵乘法运算

#include <stdio.h>
#include <stdlib.h>

#define MAX 255

/* 实矩阵相乘 */
void MatrixMul(double a[], double b[], int m, int n, int k, double c[]) 
/* 
	m:矩阵A的行数
	n:矩阵B的行数
	k:矩阵B的列数
	a为A矩阵
	b为B矩阵
	c为结果,即c = AB
*/
{
	int i, j, l, u;
	/* 逐行逐列计算乘积 */
	for (i = 0; i <= m - 1; i++)
	for (j = 0; j <= k - 1; j++)
	{
		u = i*k + j; c[u] = 0.0;
		for (l = 0; l <= n - 1; l++)
			c[u] = c[u] + a[i*n + l] * b[l*k + j];
	}
	return;
}


void main()
{
	int i, j, m, n, k;
	double A[MAX];
	double B[MAX];
	double C[MAX];
	for (i = 0; i<MAX; i++)
		C[i] = 1.0;
	puts("This is a real-matrix-multiplication program.\n");
	puts("It calculate the two matrixes C(m*k)=A(m*n)B(n*k).\n");
	printf(" >> Please input the number of rows in A, m= ");
	scanf("%d", &m);
	printf(" >> Please input the number of cols in A, n= ");
	scanf("%d", &n);
	printf(" >> Please input the number of cols in B, k= ");
	scanf("%d", &k);
	printf(" >> Please input the %d elements in A one by one:\n", m*n);
	for (i = 0; i<m*n; i++)
		scanf("%lf", &A[i]);
	printf(" >> Please input the %d elements in B one by one:\n", n*k);
	for (i = 0; i<n*k; i++)
		scanf("%lf", &B[i]);

	MatrixMul(A, B, m, n, k, C); /*计算C的结果*/
	/*格式化输出结果*/
	printf("\n >> The result of C(%d*%d)=A(%d*%d)B(%d*%d) is:\n", m, k, m, n, n, k);
	for (i = 0; i<m; i++)
	{
		for (j = 0; j<k; j++)
			printf("%10.5f    ", C[i*k + j]);
		printf("\n");
	}
	system("pause");
}

112、求解线性方程

#include <stdlib.h>
#include <math.h>
#include <stdio.h>

#define MAX 255

int Guass(double a[], double b[],int n)
{
	int *js, l, k, i, j, is, p, q;
	double d, t;
	js = (int *)malloc(n*sizeof(int));
	l = 1;
	for (k = 0; k <= n - 2; k++)
	{
		d = 0.0;
		/*下面是换主元部分,即从系数矩阵A的第K行,第K列之下的部分选出
		绝对值最大的元,交换到对角线上。*/
		for (i = k; i <= n - 1; i++)
		for (j = k; j <= n - 1; j++)
		{
			t = fabs(a[i*n + j]); /*fabs()定义在math.h中,含义是求一个浮点数的绝对值。*/
			if (t>d) { d = t; js[k] = j; is = i; }
		}
		if (d + 1.0 == 1.0) l = 0;  /*主元为0*/
		/*主元不为0的时候*/
		else
		{
			if (js[k] != k)
			for (i = 0; i <= n - 1; i++)
			{
				p = i*n + k; q = i*n + js[k];
				t = a[p]; a[p] = a[q]; a[q] = t;
			}
			if (is != k)
			{
				for (j = k; j <= n - 1; j++)
				{
					p = k*n + j; q = is*n + j;
					t = a[p]; a[p] = a[q]; a[q] = t;
				}
				t = b[k]; b[k] = b[is]; b[is] = t;
			}
		}
		if (l == 0)
		{
			free(js); printf("fail\n");
			return(0);
		}
		d = a[k*n + k];
		/* 下面为归一化部分 */
		for (j = k + 1; j <= n - 1; j++)
		{
			p = k*n + j; a[p] = a[p] / d;
		}
		b[k] = b[k] / d;
		/* 下面为矩阵A,B消元部分 */
		for (i = k + 1; i <= n - 1; i++)
		{
			for (j = k + 1; j <= n - 1; j++)
			{
				p = i*n + j;
				a[p] = a[p] - a[i*n + k] * a[k*n + j];
			}
			b[i] = b[i] - a[i*n + k] * b[k];
		}
	}

	d = a[(n - 1)*n + n - 1];
	/* 矩阵无解或有无限多解 */
	if (fabs(d) + 1.0 == 1.0)
	{
		free(js); printf("该矩阵为奇异矩阵\n");
		return(0);
	}
	b[n - 1] = b[n - 1] / d;
	/* 下面为迭代消元 */
	for (i = n - 2; i >= 0; i--)
	{
		t = 0.0;
		for (j = i + 1; j <= n - 1; j++)
			t = t + a[i*n + j] * b[j];
		b[i] = b[i] - t;
	}
	js[n - 1] = n - 1;
	for (k = n - 1; k >= 0; k--)
	if (js[k] != k)
	{
		t = b[k]; b[k] = b[js[k]]; b[js[k]] = t;
	}
	free(js);
	return(1);
}

void main()
{
	int i, n;
	double A[MAX];
	double B[MAX];
	puts("This is a program to solve N order linear equation set Ax=B.");
	puts("\n It use Guass Elimination Method to solve the equation set:");
	puts("\n    a(0,0)x0+a(0,1)x1+a(0,2)x2+...+a(0,n-1)xn-1=b0");
	puts("    a(1,0)x0+a(1,1)x1+a(1,2)x2+...+a(1,n-1)xn-1=b1");
	puts("    ......");
	puts("    a(n-1,0)x0+a(n-1,1)x1+a(n-1,2)x2+...+a(n-1,-1)xn-1=bn-1\n");
	printf(" >> Please input the order n (>1): ");
	scanf("%d", &n);
	printf(" >> Please input the %d elements of matrix A(%d*%d) one by one:\n", n*n, n, n);
	for (i = 0; i<n*n; i++)
		scanf("%lf", &A[i]);
	printf(" >> Please input the %d elements of matrix B(%d*1) one by one:\n", n, n);
	for (i = 0; i<n; i++)
		scanf("%lf", &B[i]);
	if (Guass(A, B, n) != 0) /*调用Guass消去,1为计算成功*/
		printf(" >> The solution of Ax=B is x(%d*1):\n", n);

	for (i = 0; i<n; i++) /*打印结果*/
		printf("x(%d)=%f  ", i, B[i]);
	system("pause");
}

113、阶方阵求逆

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 255

void MatrixMul(double a[], double b[], int m, int n, int k, double c[])  /*实矩阵相乘*/
/*
m:矩阵A的行数
n:矩阵B的行数
k:矩阵B的列数
a为A矩阵
b为B矩阵, c为结果,即c = AB */
{
	int i, j, l, u;
	/* 逐行逐列计算乘积 */
	for (i = 0; i <= m - 1; i++)
	for (j = 0; j <= k - 1; j++)
	{
		u = i*k + j; c[u] = 0.0;
		for (l = 0; l <= n - 1; l++)
			c[u] = c[u] + a[i*n + l] * b[l*k + j];
	}
	return;
}
/* 求矩阵的逆矩阵 */
int brinv(double a[], int n) 
/* n: 矩阵的阶数, a: 矩阵A */
{
	int *is, *js, i, j, k, l, u, v;
	double d, p;
	is = (int *)malloc(n*sizeof(int));
	js = (int *)malloc(n*sizeof(int));
	for (k = 0; k <= n - 1; k++)
	{
		d = 0.0;
		for (i = k; i <= n - 1; i++)
			/*全选主元,即选取绝对值最大的元素*/
		for (j = k; j <= n - 1; j++)
		{
			l = i*n + j; p = fabs(a[l]);
			if (p>d) { d = p; is[k] = i; js[k] = j; }
		}
		/*全部为0,此时为奇异矩阵*/
		if (d + 1.0 == 1.0)
		{
			free(is); free(js); printf(" >> This is a singular matrix, can't be inversed!\n");
			return(0);
		}
		/*行交换*/
		if (is[k] != k)
		for (j = 0; j <= n - 1; j++)
		{
			u = k*n + j; v = is[k] * n + j;
			p = a[u]; a[u] = a[v]; a[v] = p;
		}
		/*列交换*/
		if (js[k] != k)
		for (i = 0; i <= n - 1; i++)
		{
			u = i*n + k; v = i*n + js[k];
			p = a[u]; a[u] = a[v]; a[v] = p;
		}
		l = k*n + k;
		a[l] = 1.0 / a[l]; /*求主元的倒数*/
		/* a[kj]a[kk] -> a[kj] */
		for (j = 0; j <= n - 1; j++)
		if (j != k)
		{
			u = k*n + j; a[u] = a[u] * a[l];
		}
		/* a[ij] - a[ik]a[kj] -> a[ij] */
		for (i = 0; i <= n - 1; i++)
		if (i != k)
		for (j = 0; j <= n - 1; j++)
		if (j != k)
		{
			u = i*n + j;
			a[u] = a[u] - a[i*n + k] * a[k*n + j];
		}
		/* -a[ik]a[kk] -> a[ik] */
		for (i = 0; i <= n - 1; i++)
		if (i != k)
		{
			u = i*n + k; a[u] = -a[u] * a[l];
		}
	}
	for (k = n - 1; k >= 0; k--)
	{
		/*恢复列*/
		if (js[k] != k)
		for (j = 0; j <= n - 1; j++)
		{
			u = k*n + j; v = js[k] * n + j;
			p = a[u]; a[u] = a[v]; a[v] = p;
		}
		/*恢复行*/
		if (is[k] != k)
		for (i = 0; i <= n - 1; i++)
		{
			u = i*n + k; v = i*n + is[k];
			p = a[u]; a[u] = a[v]; a[v] = p;
		}
	}
	free(is); free(js);
	return(1);
}

/* 打印的方阵a的元素 */
void print_matrix(double a[], int n)
/* n:矩阵的阶数 a:矩阵a */
{
	int i, j;
	for (i = 0; i<n; i++)
	{

		for (j = 0; j<n; j++)
			printf("%13.7f\t", a[i*n + j]);
		printf("\n");
	}
}

void main()
{
	int i, j, n = 0;
	double A[MAX], B[MAX], C[MAX];
	static double a[4][4] = { { 0.2368, 0.2471, 0.2568, 1.2671 },
	{ 1.1161, 0.1254, 0.1397, 0.1490 },
	{ 0.1582, 1.1675, 0.1768, 0.1871 },
	{ 0.1968, 0.2071, 1.2168, 0.2271 } };
	static double b[4][4], c[4][4];
	puts("**********************************************************");
	puts("*    This program is to inverse a square matrix A(nxn).  *");
	puts("**********************************************************");
	while (n <= 0)
	{
		printf(" >> Please input the order n of the matrix (n>0): ");
		scanf("%d", &n);
	}

	printf(" >> Please input the elements of the matrix one by one:\n >> ");
	for (i = 0; i<n*n; i++)
	{
		scanf("%lf", &A[i]);
		B[i] = A[i];
	}
	for (i = 0; i<4; i++)
	for (j = 0; j<4; j++)
		b[i][j] = a[i][j];

	i = brinv(A, n);

	if (i != 0)
	{
		printf("    Matrix A:\n");
		print_matrix(B, n);
		printf("\n");
		printf("    A's Inverse Matrix A-:\n");
		print_matrix(A, n);
		printf("\n");
		printf("    Product of A and A- :\n");
		MatrixMul(B, A, n, n, n, C);
		print_matrix(C, n);
	}
	system("pause");
}

114、复矩阵乘法

#include <stdio.h>
#include <stdlib.h>
#define MAX 255

/* 复矩阵相乘 */
void CMatrixMul(double ar[], double ai[], double br[], double bi[], int m, int n, int k, cr[], ci[])
/*
m是矩阵A的行数
n是矩阵B的行数
k是矩阵B的列数
ar,br,cr分别是矩阵A,B,C的实部
ai,bi,ci分别是矩阵A,B, C的虚部
*/
{
	int i, j, l, u, v, w;
	double p, q, s;
	for (i = 0; i <= m - 1; i++)
	for (j = 0; j <= k - 1; j++)
	{
		u = i*k + j;
		cr[u] = 0.0; ci[u] = 0.0;
		for (l = 0; l <= n - 1; l++)
		{
			v = i*n + l; w = l*k + j;
			p = ar[v] * br[w];
			q = ai[v] * bi[w];
			s = (ar[v] + ai[v])*(br[w] + bi[w]);
			cr[u] = cr[u] + p - q;
			ci[u] = ci[u] + s - p - q;
		}
	}
	return;
}
/* 打印的矩阵A(m*n)的元素 */
void print_matrix(double A[], int m, int n)
 /*
 m,n:矩阵的阶数
 A: 矩阵A
 */
{
	int i, j;
	for (i = 0; i<m; i++)
	{
		for (j = 0; j<n; j++)
			printf("%13.7f\t", A[i*n + j]);
		printf("\n");
	}
}
void main()
{
	int i, j, n, m, k;
	double Ar[MAX], Br[MAX], Cr[MAX], Ai[MAX], Bi[MAX], Ci[MAX];
	static double cr[3][4], ci[3][4];
	static double ar[3][4] = { { 1.0, 2.0, 3.0, -2.0 }, /*矩阵A的实部*/
	{ 1.0, 5.0, 1.0, 3.0 },
	{ 0.0, 4.0, 2.0, -1.0 } };
	static double ai[3][4] = { { 1.0, -1.0, 2.0, 1.0 }, /*矩阵A的虚部*/
	{ -1.0, -1.0, 2.0, 0.0 },
	{ -3.0, -1.0, 2.0, 2.0 } };
	static double br[4][4] = { { 1.0, 4.0, 5.0, -2.0 }, /*矩阵B的实部*/
	{ 3.0, 0.0, 2.0, -1.0 },
	{ 6.0, 3.0, 1.0, 2.0 },
	{ 2.0, -3.0, -2.0, 1.0 } };
	static double bi[4][4] = { { -1.0, -1.0, 1.0, 1.0 }, /*矩阵B的虚部*/
	{ 2.0, 1.0, 0.0, 5.0 },
	{ -3.0, 2.0, 1.0, -1.0 },
	{ -1.0, -2.0, 1.0, -2.0 } };
	puts("**********************************************************");
	puts("*    This is a complex-matrix-multiplication program.    *");
	puts("*    It calculate the two matrixes C(m*k)=A(m*n)B(n*k).  *");
	puts("**********************************************************");
	printf(" >> Please input the number of rows in A, m= ");
	scanf("%d", &m);
	printf(" >> Please input the number of cols in A, n= ");
	scanf("%d", &n);
	printf(" >> Please input the number of cols in B, k= ");
	scanf("%d", &k);
	printf(" >> Please input the %d elements in Ar one by one:\n >> ", m*n);
	for (i = 0; i<m*n; i++)
		scanf("%lf", &Ar[i]);
	printf(" >> Please input the %d elements in Ai one by one:\n >> ", m*n);
	for (i = 0; i<m*n; i++)
		scanf("%lf", &Ai[i]);
	printf(" >> Please input the %d elements in Br one by one:\n >> ", n*k);
	for (i = 0; i<n*k; i++)
		scanf("%lf", &Br[i]);
	printf(" >> Please input the %d elements in Bi one by one:\n >> ", n*k);
	for (i = 0; i<n*k; i++)
		scanf("%lf", &Bi[i]);
	CMatrixMul(Ar, Ai, Br, Bi, m, n, k, Cr, Ci); /*进行计算*/
	/*输出乘积结果的实部*/
	printf(" Real part of C(%d*%d)=A(%d*%d)*B(%d*%d):\n", m, k, m, n, n, k);
	print_matrix(Cr, m, k);
	/*输出乘积结果的虚部*/
	printf(" Complex part of C(%d*%d)=A(%d*%d)*B(%d*%d):\n", m, k, m, n, n, k);
	print_matrix(Ci, m, k);
	system("pause");
}

115、求定积分

#include <stdio.h>
#include <math.h>
#include <stdlib.h>


/* 要进行计算的被积函数 */
double fsimpf(double x) 
{
	double y;
	y = log(1.0 + x) / (1.0 + x*x);
	return(y);
}

/* 辛普森算法 */
double fsimp(double a, double b, double eps) 
/*a为积分下限,b为积分上限,eps是希望达到的精度*/
{
	int n, k;
	double h, t1, t2, s1, s2, ep, p, x;
	n = 1; h = b - a;
	t1 = h*(fsimpf(a) + fsimpf(b)) / 2.0;  /* 用梯形公式求出一个大概的估值 */
	s1 = t1;
	ep = eps + 1.0;
	while (ep >= eps)
	{
		/* 用梯形法则计算 */
		p = 0.0;
		for (k = 0; k <= n - 1; k++)
		{
			x = a + (k + 0.5)*h;
			p = p + fsimpf(x);
		}
		t2 = (t1 + h*p) / 2.0;
		/* 用辛普森公式求精 */
		s2 = (4.0*t2 - t1) / 3.0;
		ep = fabs(s2 - s1);
		t1 = t2; s1 = s2; n = n + n; h = h / 2.0;
	}
	return(s2);
}
void main()
{
	double a, b, eps, t;
	a = 0.0; b = 1.0; eps = 0.0000001;
	puts("**********************************************************");
	puts("*         This program is to calculat the Value of       *");
	puts("*          a definite integral by Simpson Method.        *");
	puts("**********************************************************");
	t = fsimp(a, b, eps);
	puts("\n----------------------------------------------------------");
	printf(" >> The result of definite integral is : \n");
	printf(" >> SIGMA(0,1)ln(1+x)/(1+x^2)dx = ");
	printf("%e\n", t);
	puts("----------------------------------------------------------");
	system("pause");
}

116、求满足特异条件的数列

#include <stdio.h>
#include <stdlib.h>
#define NUM 10      /* 允许分解的最大元素数量 */
int i[NUM];        /* 记录分解出的数值的数组 */

void main()
{
	int sum, n, total, k, flag, count = 0;
	puts("*********************************************************");
	puts("*   This is a program to get number sequence with       *");
	puts("* special characteristic. Input n and m,get the sequence*");
	puts("* S1,S2,...,Sn, where S1+S2+...+Sn=m and S1>=S2>=...>=Sn*");
	puts("* e.g.n=4,m=8,S: 5 1 1 1,4 2 1 1,3 3 1 1,3 2 2 1,2 2 2 2*");
	puts("*********************************************************");
	printf(" >> Input element number of the sequence (n<=10): ");
	scanf("%d", &n);
	printf(" >> Input the sum of the elements (m<=20): ");
	scanf("%d", &total);
	sum = 0;                 /*当前从后向前k个元素的和*/
	k = n;                   /*从后向前正在处理的元素下标*/
	i[n] = 1;             /*将最后一个元素的值置为1作为初始值*/
	printf(" >> Possible sequences are as follows:\n");
	while (1)
	{
		if (sum + i[k]<total)     /*若后k位的和小于指定的total*/
		if (k <= 1)            /*若正要处理的是第一个元素*/
		{
			i[1] = total - sum; flag = 1;
		}     /*则计算第一个元素的并置标记*/
		else{
			sum += i[k--];
			i[k] = i[k + 1];        /*置第k位的值后k-1*/
			continue;         /*继续向前处理其它元素*/
		}
		else if (sum + i[k]>total || k != 1)   /*若和已超过total或不是第一个元素*/
		{
			sum -= i[++k]; flag = 0;
		}      /*k向后回退一个元素*/
		else flag = 1;        /*sum+i[k]=total&&k=1 则设置flag标记*/
		if (flag)
		{
			printf(" No.%2d: ", ++count);
			for (flag = 1; flag <= n; ++flag)
				printf("%d ", i[flag]);
			printf("\n");
		}
		if (++k>n)     /*k向后回退一个元素后判断是否已退出最后一个元素*/
			break;
		sum -= i[k];
		i[k]++;        /*试验下一个分解*/
	}
	system("pause");
}

117、超长正整数的加法

#include<stdio.h>
#include<stdlib.h>

#define HUNTHOU 10000
typedef struct node{
	int data;
	struct node *next;
}NODE;                 /*定义链表结构*/

NODE *insert_after(NODE *u, int num);     /* 在u结点后插入一个新的NODE,其值为num */
NODE *addint(NODE *p, NODE *q);           /* 完成加法操作返回指向*p+*q结果的指针 */
void printint(NODE *s);
NODE *inputint(void);

void main()
{
	NODE *s1, *s2, *s;
	NODE *inputint(), *addint(), *insert_after();
	puts("*********************************************************");
	puts("*              This program is to calculate             *");
	puts("*       the addition of king sized positive integer.    *");
	puts("*********************************************************");
	printf(" >> Input S1= ");
	s1 = inputint();            /*输入被加数*/
	printf(" >> Input S2= ");
	s2 = inputint();            /*输入加数*/
	printf(" >> The addition result is as follows.\n\n");
	printf("    S1= "); printint(s1); putchar('\n');     /*显示被加数*/
	printf("    S2= "); printint(s2); putchar('\n');     /*显示加数*/
	s = addint(s1, s2);                                 /*求和*/
	printf(" S1+S2="); printint(s); putchar('\n');    /*输出结果*/
	system("pause");
}
NODE *insert_after(NODE *u, int num)
{
	NODE *v;
	v = (NODE *)malloc(sizeof(NODE));      /*申请一个NODE*/
	v->data = num;                         /*赋值*/
	u->next = v;                           /*在u结点后插入一个NODE*/
	return v;
}
NODE *addint(NODE *p, NODE *q)         /*完成加法操作返回指向*p+*q结果的指针*/
{
	NODE *pp, *qq, *r, *s, *t;
	int total, number, carry;
	pp = p->next; qq = q->next;
	s = (NODE *)malloc(sizeof(NODE));     /*建立存放和的链表表头*/
	s->data = -1;
	t = s; carry = 0;                      /*carry:进位*/
	while (pp->data != -1 && qq->data != -1)    /*均不是表头*/
	{
		total = pp->data + qq->data + carry;     /*对应位与前次的进位求和*/
		number = total%HUNTHOU;             /*求出存入链中部分的数值 */
		carry = total / HUNTHOU;              /*算出进位*/
		t = insert_after(t, number);         /*将部分和存入s向的链中*/
		pp = pp->next;                         /*分别取后面的加数*/
		qq = qq->next;
	}
	r = (pp->data != -1) ? pp : qq;          /*取尚未自理完毕的链指针*/
	while (r->data != -1)              /*处理加数中较大的数*/
	{
		total = r->data + carry;         /*与进位相加*/
		number = total%HUNTHOU;        /*求出存入链中部分的数值*/
		carry = total / HUNTHOU;         /*算出进位*/
		t = insert_after(t, number);     /*将部分和存入s指向的链中*/
		r = r->next;                   /*取后面的值*/
	}
	if (carry) t = insert_after(t, 1);     /*处理最后一次进位*/
	t->next = s;                   /*完成和的链表*/
	return s;                     /*返回指向和的结构指针*/
}
NODE *inputint(void)     /*输入超长正整数*/
{
	NODE *s, *ps, *qs;
	struct number {
		int num;
		struct number *np;
	}*p, *q;
	int i, j, k;
	long sum;
	char c;
	p = NULL;     /*指向输入的整数,链道为整数的最低的个位,链尾为整数的最高位*/
	while ((c = getchar()) != '\n')     /*输入整数,按字符接收数字*/
	if (c >= '0'&&c <= '9')           /*若为数字则存入*/
	{
		q = (struct number *)malloc(sizeof(struct number));    /*申请空间*/
		q->num = c - '0';           /*存入一位整数*/
		q->np = p;                /*建立指针*/
		p = q;
	}
	s = (NODE *)malloc(sizeof(NODE));
	s->data = -1;                  /*建立表求超长正整数的链头*/
	ps = s;
	while (p != NULL)        /*将接收的临时数据链中的数据转换为所要求的标准形式*/
	{
		sum = 0; i = 0; k = 1;
		while (i<4 && p != NULL)          /*取出低四位*/
		{
			sum = sum + k*(p->num);
			i++; p = p->np; k = k * 10;
		}
		qs = (NODE *)malloc(sizeof(NODE));          /*申请空间*/
		qs->data = sum;                     /*赋值,建立链表*/
		ps->next = qs;
		ps = qs;
	}
	ps->next = s;
	return s;
}

void printint(NODE *s)
{
	if (s->next->data != -1)         /*若不是表头,则输出*/
	{
		printint(s->next);             /*递归输出*/
		if (s->next->next->data == -1)
			printf("%d", s->next->data);
		else{
			int i, k = HUNTHOU;
			for (i = 1; i <= 4; i++, k /= 10)
				putchar('0' + s->next->data % (k) / (k / 10));
		}
	}
}

118、绘制直线

#include <graphics.h>
#include <stdlib.h>

void main()
{
	int gdriver = DETECT, gmode;
	initgraph(&gdriver, &gmode, "c:\\tc");
	cleardevice();
	line(160, 120, 480, 120);
	line(480, 120, 480, 360);
	line(480, 360, 160, 360);
	line(160, 360, 160, 120);
	system("pause");
	closegraph();
}

119、绘制圆

#include <graphics.h>
#include <stdlib.h>

void main()
{
	int gdriver = DETECT, gmode;
	initgraph(&gdriver, &gmode, "c:\\tc");
	cleardevice();
	moveto(160, 120);
	lineto(480, 120);
	lineto(480, 360);
	lineto(160, 360);
	lineto(160, 120);
	system("pause");
	closegraph();
}

120、绘制圆弧

#include <graphics.h>
#include <stdlib.h>

void main()
{
	int gdriver = DETECT, gmode;
	initgraph(&gdriver, &gmode, "c:\\tc");
	cleardevice();
	moveto(160, 120);
	linerel(320, 0);
	linerel(0, 240);
	linerel(-320, 0);
	linerel(0, -240);
	system("pause");
	closegraph();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jxiepc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值