您的位置:首页 > 其它

实验C—5 任意十进制数转化为二进制

2017-10-16 22:51 176 查看
设计思路:

十进制转二进制无非相除取余,然后余数倒序输出,即为先进后出,应该使用栈。

代码:

#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;
}实验测试图:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: