求用C语言版数据结构做的十进制转换成其它进制(2,8,16)的程序!!!
有会的帮个忙。。。感激涕零!!
用栈
#include <stdio.h> typedef struct tagSTACK { int stack[255]; int top; } STACK; STACK s; void push (int i) { s.top++; s.stack[s.top] = i; } int pop () { int ret; if (s.top > -1) { ret = s.stack[s.top]; s.top--; return ret; } return -1; } void Bin (int i, int k, char str[]) { int j, ret; while (i) { push (i % k); i /= k; } for (j = 0; ret = pop (), ret != -1; ++j) { if (ret > 9) { str[j] = ret + 'A' - 10; } else { str[j] = ret + '0'; } } str[j] = 0; } int main (void) { int i; char result[255]; s.top = -1; scanf ("%d", &i); Bin (i, 2, result); printf ("二进制:\t\t%s\n", result); s.top = -1; Bin (i, 8, result); printf ("八进制:\t\t%s\n", result); Bin (i, 16, result); printf ("十六进制:\t%s\n", result); return 0; }
#include <iostream> #include <stack> using namespace std; int NumConvert(int n,int k); int main() { int n,k; cout<<"请输入十进制数:"<<endl; cin>>n; cout<<"请输入想转化的进制:"<<endl; cin>>k; NumConvert(n,k); } int NumConvert(int n,int k) { stack<char> s; int flag=0; if(n<0) { n=-n; flag=1; } while(n) { char x; int m=n%k; if(m>=10) x='A'+m-10; else x='0'+m; s.push(x); n=n/k; } if(flag==1) s.push('-'); while(!s.empty()) { char e=s.top(); s.pop(); cout<<e; } return 0; }我写的!