题目内容
利用“顺序队列”将十进制的小数部分转base进制(要考虑小数位保留位数)。
个人解法
//由于本人已彻底从vs转到了vscode,且使用的是MinGW64编译环境,因此今后不会再使用#define_CRT_SECURE_NO_WARNINGS #include#include #define MaxSize 100 //最大队列长度 #define Succeed 1 #define Error 0 #define Overflow -1 typedef int QElemType; typedef struct { QElemType *base; //初始化的动态分配存储空间 int front; //头指针,若队列不空,指向队列头元素 int rear; //尾指针,若队列不空,指向队列尾元素的下一个位置 } SqQueue; //初始化循环队列 void InitQueue(SqQueue &Q) { Q.base = (QElemType *)malloc(MaxSize * sizeof(QElemType)); if (!Q.base) exit(Overflow); //存储空间分配失败 Q.front = Q.rear = 0; //构造一个空队列 printf("初始化成功!"); } //返回Q的元素个数,即队列当前长度 int QueueLength(SqQueue &Q) { return (Q.rear - Q.front + MaxSize) % MaxSize; } //判空 bool IsEmpty(SqQueue &Q) { QElemType e; if ((Q.rear + 1) % MaxSize == Q.front) return true; else return false; } //判满 bool IsFull(SqQueue &Q) { QElemType e; if (Q.front == Q.rear) return true; else return false; } //入队 void EnQueue(SqQueue &Q) { QElemType e; if (IsEmpty(Q)) printf("队列已满!"); else { printf("输入欲插入的元素:"); scanf(" %d", &e); Q.base[Q.rear] = e; //插入元素e为Q的新的队尾元素 Q.rear = (Q.rear + 1) % MaxSize; // rear + 1 printf("插入成功!"); } } //出队 void DeQueue(SqQueue &Q) { QElemType e; if (IsFull(Q)) printf("队列为空!"); else { printf("输入欲删除的元素:"); scanf(" %d", &e); e = Q.base[Q.front]; //删除Q的队头元素并将其值赋给e Q.front = (Q.front + 1) % MaxSize; // front + 1 printf("删除成功!"); } } void Conversion() { SqQueue Q; int base; //我原先以为base进制的意思是用存储空间base的地址数据,结果把*Q.base放进去后出大问题(有兴趣可以试试,总之输出结果很离谱) float input; QElemType output; InitQueue(Q); printf("请输入待转的十进制数:n"); scanf("%f", &input); printf("请输入进制数:n"); scanf("%d", &base); if (input == 0) exit(Error); int integer = input / 1; //分离整数部分 float decimal = input - (float)integer; for (int i = 0; i < 9; i++) //遍历输出结果,这里设定小数位保留位数为9+1位 { decimal = decimal * base; //小数自乘以目标进制数 Q.base[Q.rear] = (QElemType)decimal; //插入取整结果为Q的新的队尾元素 Q.rear = (Q.rear + 1) % MaxSize; decimal = decimal - (QElemType)decimal; } printf("小数部分转换为%d进制的值为:n.", base); while (!IsEmpty(Q)) { output = Q.base[Q.front]; //删除Q的队头元素并将其值赋给result Q.front = (Q.front + 1) % MaxSize; printf("%d", output); //如果输出结果里看到-1163005939这类就说明数组越界了,但不影响代码运行 } } int main() { Conversion(); system("pause"); return 0; }
运行结果:
虽说数组越界并不影响编译,但还望热心大佬出手相助,在下不胜感激。



