十进制转为二进制


#include <iostream>
using namespace std;
struct Node
{
    int data;
    Node *next;
};
 
class SLL
{
private:
    Node *top;
public:
    SLL();
    void Push(int i);
    int Pop();
    bool IsEmpty();
    void wPush(int i);
};
SLL::SLL()
{
    top=new Node;
    top->next=NULL;
}
void SLL::Push(int i)

    Node *p;
    p=new Node;
    p->data=i;
    p->next=top->next;
    top->next=p;
}
int SLL::Pop()
{
    Node *p;
    int x;
    x=top->next->data;
    p=top->next;
    top->next=top->next->next;
    delete p;
    return x;
}
bool SLL::IsEmpty()
{
    return (top->next==NULL);
}
void SLL::wPush(int i)
{
    Node *p,*q;
    p=top;
    q=new Node;
    while(1)
    {
        if(p->next==NULL)
            break;
        else
            p=p->next;
    }
    q->data=i;
    q->next=NULL;
    p->next=q;
 
}
void ZB(int x)
{
    SLL s1;
    int k;
    while(x!=0)
    {
        k=x%2;
        s1.Push(k);
        x=x/2;
    }
    while(!s1.IsEmpty())
    {
        cout<<s1.Pop();
    }
}
void XB(double x)
{
    SLL s1;
    int k;
    while(x!=1)
    {
        k=x*2;
        s1.wPush(k);
        x=x*2;
    }
    while(!s1.IsEmpty())
    {
        cout<<s1.Pop();
    }
    cout<<endl;
}
int main()
{
    SLL s1;
    double x;
    double y;
    int i;
    while(cin>>x)
    {
        if(x==0)
            break;
        else
        {
            i=x;
            y=x-i;
            if(i==0)
            {
                cout<<"0.";
                XB(y);
            }
            else if(y==0)
            {
                ZB(i);
                cout<<endl;
            }
            else if(i!=0&&y!=0)
            {
                ZB(i);
                cout<<".";
                XB(y);
            }  
        }
    }
      return 0;
}

猜你喜欢

转载自blog.csdn.net/banquet79/article/details/80199760