实验C—5 任意十进制数转化为二进制
程序员文章站
2022-03-08 15:38:10
...
设计思路:
十进制转二进制无非相除取余,然后余数倒序输出,即为先进后出,应该使用栈。
代码:
#include<iostream>
using namespace std;
class Translate {
int data;
Translate *next, *top;
public:
Translate() { top = NULL; }
void push(int);
void pop();
};
void Translate::push(int x) {
Translate *p = new Translate;
p->data = x; p->next = top; top = p;
}
void Translate::pop() {
Translate *p = new Translate;
while (top)
{
p = top;
cout << top->data;
top = top->next;
delete p;
}
}
void main() {
int n; Translate p;
cout << "输入十进制数:" << endl; cin >> n;
while (n != 0)
{
p.push(n % 2);
n /= 2;
}cout << endl;
cout << "二进制数为:";
p.pop();
cout << endl;
}
实验测试图: