English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I dont know what is wrong it is supposed to convert decimal to binary!
Can I declare Arrays whose number of elements is variable?
How?
This program already output
the binary equivalent but it has extra numbers
#include
void main ()
{
int num,xnum,dgts,counter;
cout<<"Enter Number"< cin>>num;
if(num<=1)
cout< else
{
xnum=num;
dgts=0;
while(xnum>=1)
{
xnum=xnum/2;
dgts+=1;
}
int bnr[50];
for (counter=0;counter {
bnr[counter]=num%2;
num=num/2;
}
cout< while(dgts>=0)
{
dgts=dgts-1;
cout< }
}
}

2007-03-05 18:00:08 · 2 answers · asked by topher09 2 in Computers & Internet Programming & Design

2 answers

Everything is right in the program. Only at the end, while printing the number, you are making a mistake. The while loop should be
"while (dgts>0)" instead of while(dgts>=0).
Whats happening is at the end, when dgts = 0;

dgts = dgts -1, will make dgts = -1;
and then you are trying to access bnr[-1], which is illegal.

And certainly you can use a dynamic array, instead of static. Using dynamic arrays you can have whose number of elements is variable.

In above example instead of int bnr[50], you can simply declare int * bnr;
And then when you know how mnay elements you need, you can allocate memory as :

bnr = (int *)malloc(dgts * sizeof(int));
The rest of the program will be as it is.
Here is the entire right program, with dynamic memory.

#include
void main ()
{
int num,xnum,dgts,counter;
cout<<"Enter Number"< cin>>num;
if(num<=1)
cout< else
{
xnum=num;
dgts=0;
while(xnum>=1)
{
xnum=xnum/2;
dgts+=1;
}
int *bnr;
bnr = (int *)malloc(dgts * sizeof(int));
for (counter=0;counter {
bnr[counter]=num%2;
num=num/2;
}
cout< while(dgts>0)
{
dgts=dgts-1;
cout< }
}
}

2007-03-05 18:47:58 · answer #1 · answered by manoj Ransing 3 · 1 0

OK, I haven't compiled your given code in my compiler, but looking at the code, and assuming that you are getting the binary equivalent, with extra digits means that your array bnr[ ] is printing out ALL the elements in it.
I suggest you first initialize the array before assigning it any value. Then, you can assign a NULL character to index after that last element of the array. This should solve the problem.
Good Luck!

2007-03-05 18:08:24 · answer #2 · answered by A.Samad Shaikh 2 · 1 0

fedest.com, questions and answers