2.十进制转换成二进制
算法:利用while语句
当所输入的数不为1时,执行while循环
在while循环中将输入的数插入顺序栈中
只支持整形数据
#include
using namespace std;
const int stacksize = 10;
class seqstack
{
public:
seqstack() { top = -1; }
~seqstack() {};
void push(int x);
int pop();
int gettop() { if (top != 1) return data[top]; }
int empty() { return(top == -1) ? 1 : 0; }
void print();
private:
int data[stacksize];
int top;
};
void seqstack::push(int x)
{
if (top == stacksize - 1)throw"上溢";
top++;
data[top] = x;
}
int seqstack::pop()
{
if (top == -1)throw"下溢";
int x = data[top--];
return x;
}
void seqstack::print()
{
for (int i = top; i >-1; i--)
cout << data[i];
}
int main()
{
int x;
seqstack a;
cin >> x;
while (x != 1)
{
if (x % 2 == 0)
{
a.push(0);
x = 0.5*x;
}
else
{
a.push(1);
x = (x - 1)*0.5;
}
}
a.push(1);
a.print();
}