Experimental purpose and requirements: Familiar with using the stack to complete the conversion of m-ary numbers to n-ary numbers. |
||||||||||
Experiment content: Use the stack to complete the number system conversion. Purpose: To master the application of the last-in-first-out principle of the stack in solving practical problems. Content: Use the stack to perform number system conversion, taking m-ary number to n-ary number conversion as an example. Use the stack to write a program that satisfies the following requirements: For any non-negative m-ary number input, print out the n-ary number equal to its value. The specific implementation process: 1. Define the stack, including initial allocation, stack top pointer, and stack bottom pointer. 2. Define the functions that need to be used. (1) Construct an empty stack: InitStack() (2) Push into the stack: Push () (3) Out of the stack: Pop() (4): Number system conversion function: Conversion() 3. Connect the function. |
||||||||||
Experimental steps and procedures: #include<stdio.h> #include<stdlib.h> #include<string.h> #define SIZE 100 typedef struct { int *base; int *top; int size; }sqstack; sqstack initstack() { sqstack s; s.base = (int *)malloc(SIZE * sizeof(int)); s.top = s.base; s.size = 0; return s; } sqstack push(sqstack s, int e) { *s.top = e; s.top++; s.size++; return s; } sqstack pop(sqstack s) { if (s.top == s.base) { return s; } s.top--; return s; } int tranto10(char *ch, int m) { int res = 0; for (int i = 0; i < strlen(ch); i++) { if (ch[i] >= '0'&&ch[i] <= '9') { res = res * m + ch[i] - '0'; } if (ch[i] >= 'A'&&ch[i] <= 'Z') { res = res * m + ch[i] - 'A' + 10; } } return res; } sqstack tranton(int data, int n) { sqstack s; s = initstack(); while (data) { s=push(s, data%n); data = data / n; } return s; } void print(sqstack s) { while (1) { s = pop(s); int c = *s.top; if (c >= 10) { printf("%c ", 'A' + c - 10); } else { printf("%d ", c); } if (s.top==s.base) break; } printf("\n"); } int main() { int m, n; printf("请输入转化前后的进制,以空格分隔\n"); scanf("%d %d", &m, &n); printf("请输入 %d 进制数字\n", m); char str[100] = { 0 }; scanf("%s", str); int ten = tranto10(str, m); sqstack s = tranton(ten, n); printf("转化后的结果如下:\n"); print(s); return 0; } |
||||||||||
运行结果: 结果分析与讨论:
|
C language/c++ (data structure) example of number system conversion of stack (stack and queue) (3/7)
Guess you like
Origin blog.csdn.net/qq_59819866/article/details/131450948
Recommended
Ranking