十进制整数转换,使用链栈实现,实验报告
-
内容:
将十进制整数num转换为r进制数,其转换方法为辗转相除法,要求用链栈实现
-
算法分析:
程序中设计了四个函数:
➢函数IiStack用来初始化一个顺序栈:
➢函数Emply(用来实现栈的判空操作:
➢函数 Pop0用来实现元素的出栈操作:
➢函数Convert)用来实现数制转换算法。
数值转换问题需要用到栈的基本操作,程 序中用三个函数分别实现链栈的入栈、判断栈空和出栈操作。主函数有两个输入,即输入待转化的数和要转化的进制,函数Convert算法思想为:对待转换的数先判断正负,用f–else 语句分别实现正数和负数的转化,转换的思想是利用算数运算中的取余和取整操作,借助于栈的操作,进行辗转相除来实现。
-
概要设计:
dates
-Push(linkstack* top, datatype x):int
-Empty(linkstack top):int
-Pop(linkstack* top,datatype*x):int
Convert(int num, int mode):void
-
源码
#include<stdio.h>
#include<stdlib.h>
typedef int datatype;
typedef struct node
{
datatype data;
struct node* next;}
*linkstack;
int Push(linkstack* top, datatype x){ linkstack s = (linkstack)malloc(sizeof(struct node)); if (s == NULL)
return 0;
s->data = x;
s->next = (*top);
(*top) = s;
return 1;}int Empty(linkstack top){
if (top == NULL)
return 1;
return 0;}
int Pop(linkstack* top, datatype* x){
if (top != NULL)
{
linkstack p = (*top); (*x) = (*top)->data;
(*top) = (*top)->next;
free(p);
return 1; }
return 0;}
void Convert(int num, int mode){ int h;
linkstack top = NULL; printf("转换结果为:");
if (num > 0)
{ while (num != 0) { h = num % mode; Push(&top, h);
num = num / mode; }
while (!Empty(top))
{ Pop(&top, &h); printf("%d", h); } printf("\n"); } else if (num < 0) { printf("-"); num = num * (-1); while (num != 0) { h = num % mode; Push(&top, h); num = num / mode; } while (!Empty(top)) { Pop(&top, &h); printf("%d", h); } printf("\n"); } else printf("%d\n", 0);}void main(){ int num, mode; printf("\n 输入要转化的数:"); scanf_s("%d", &num); printf("输入要转化的进制:"); scanf_s("%d", &mode); Convert(num, mode);}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)