My code is work but the answer didn't appear.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Bong2Dy
    New Member
    • Dec 2014
    • 2

    My code is work but the answer didn't appear.

    Code:
    #include<iostream.h>
    //#include<process.h>
    #define Max 10
    class Binary{
    		int data[Max];
    		int top;
    	public:
    		int empty(){top=-1;return -1;}
    		int full();
    		void push(int);
    		int pop(int);
    };
    int Binary::full(){
    	if(top==Max-1)
    		return 1;
    	else
    		return 0;
    }
    void Binary::push(int num){
    	top=top+1;
    	data[top]=num;
    }
    int Binary::pop(int num){
    	num=data[top];
    	top=top-1;
    	return num;
    }
    void main(){
    	Binary ptr;
    	int num;
    	ptr.empty();
    	cout<<"Input Number : ";cin>>num;
    	while(num!=0){
    		if(!ptr.full()){
    			ptr.push(num%2);
    			num=num/2;
    			}
    		else{
    			cout<<"Full";
    			break;
    			}
    		}
    	cout<<"In Binary : ";
    	while(!ptr.empty()){
    		num=ptr.pop(num);
    		cout<<num;
    		}
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Your program is reaching the end of main() and there is nothing there to stop it so it goes away.

    Add a statement at the end of main to enter a character. That will stop the program until you press the enter key . Now you have time to see what was displayed.
    Last edited by weaknessforcats; Dec 26 '14, 06:33 PM.

    Comment

    • Bong2Dy
      New Member
      • Dec 2014
      • 2

      #3
      Example I input 10 and my output is :

      Input Number : 10
      In Binary :

      // It didn't show answer in Binary

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Your code is not working.

        At the end of main() there is:

        Code:
        	cout << "In Binary : ";
        	while (!ptr.empty()){
        		num = ptr.pop(num);
        		cout << num;
        	}
        but ptr.empty() always returns -1 and that causes an exit of the loop.

        Beyond that, the ptr.data, for 10, contains 0101 and some garbage values. 0101 is not 10. It's 5.

        I found this out in a couple of minutes using the debugger that comes with my compiler. At this point, I would learn how to use your debugger so you can step through the code and see what's going on. The debugger will let you see the contents of all your variables as you go aong.

        Comment

        Working...