利用“顺序队列”将十进制的小数部分转n进制(要考虑小数位保留位数)

时间:2021-06-03 23:54:17   收藏:0   阅读:31


#include<stdio.h>
#include<stdlib.h>
#define MAXQSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -2

typedef int QElemType;
typedef int status;
typedef struct{
QElemType *base;
int front;
int rear;
}SqQueue;//定义

status InitQueue(SqQueue &Q){
Q.base=(QElemType*)malloc(MAXQSIZE*sizeof(QElemType));//动态申请空间
if(!Q.base) exit(OVERFLOW);
Q.front=Q.rear=0;//初值为0 下标
return OK;
} //初始化

status EnQueue(SqQueue &Q,QElemType e){
if((Q.rear+1)%MAXQSIZE==Q.front){//判满
return ERROR;
}
Q.base[Q.rear]=e;//值给队尾
Q.rear=(Q.rear+1)%MAXQSIZE;
return OK;
} //入队列

status DeQueue(SqQueue &Q,QElemType &e){
if(Q.front==Q.rear) return ERROR;//判空
e=Q.base[Q.front];
Q.front=(Q.front+1)%MAXQSIZE;
return OK;
}//出队列

int QueueEmpty(SqQueue Q){
return(Q.front==Q.rear);
}//判空

void conversion(double n,int L){//n是小数 L是进制
int m,x=5; //整数部分
QElemType e;//接收出队列的数
SqQueue Q;
InitQueue(Q);//构造空队列
while(n&&x!=0){
n=n*L;
m=(int)n;//n强制int型
EnQueue(Q,m);//入队列 用空队列Q装n*L取整的数
n=n-m;
x--;
}
while(!QueueEmpty(Q)){
DeQueue(Q,e);//Q队列出 数据在e上
printf("%x",e); //显示转换后的数 错误的是没有显示数据 错误全部混乱
}
} //小数转十进制

int main(){
double n;
int L;
printf("请输入十进制的小数:");
scanf("%lf",&n);
printf("请输入要转换的进制:");
scanf("%d",&L);
printf("转换后为:0.");
conversion(n,L);
return 0;
}

原文:https://www.cnblogs.com/cherrysnake/p/14847425.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!