Output not right

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Smitsky

    #1

    Output not right

    Why do I get (using Dev-C++) "111," when I should be getting "101" when I
    enter "5?" I never get a "0" as an output. Can anyone let me know why?
    Thanks. Steve

    //----------------------------Code Starts------------------------------->

    #include<stack>
    #include<iostre am>

    using namespace std;

    int main()
    {
    stack<int> s;
    int number;
    int digit;
    cout<<"Please enter a decimal number to convert to binary.\n";
    cin>>number;

    while(number>0)
    {
    digit=number%2;
    s.push(digit);
    number=number/2;
    }

    while(!s.empty( ))
    {
    s.pop();
    cout<<digit;
    }

    cout<<endl;

    return 0;
    }

    //-----------------------------End Code---------------------------->


  • Victor Bazarov

    #2
    Re: Output not right

    "Smitsky" <smitsky@mindsp ring.com> wrote...[color=blue]
    > Why do I get (using Dev-C++) "111," when I should be getting "101" when I
    > enter "5?" I never get a "0" as an output. Can anyone let me know why?
    > Thanks. Steve
    >
    > //----------------------------Code Starts------------------------------->
    >
    > #include<stack>
    > #include<iostre am>
    >
    > using namespace std;
    >
    > int main()
    > {
    > stack<int> s;
    > int number;
    > int digit;
    > cout<<"Please enter a decimal number to convert to binary.\n";
    > cin>>number;
    >
    > while(number>0)
    > {
    > digit=number%2;
    > s.push(digit);
    > number=number/2;
    > }
    >
    > while(!s.empty( ))
    > {
    > s.pop();
    > cout<<digit;[/color]

    You're printing some kind of left-over from the former processing.
    Shouldn't you be printing

    s.top();

    (and actually _before_ you pop it) ?
    [color=blue]
    > }
    >
    > cout<<endl;
    >
    > return 0;
    > }
    >
    > //-----------------------------End Code---------------------------->
    >[/color]


    Comment

    • Ashes

      #3
      Re: Output not right

      Hi Steve

      You forgot to add the following statement before popping the stack in the
      while loop:

      digit = s.top();

      It is currently displaying the value of digit as it was in the last
      assignment of digit=number%2.

      Regards
      Ashley Visagie

      Comment

      Working...