-
Debugging question
Hi guys, im kinda new here, so if i make a newbi mistake please go easy on me.
Well Im trying to make a program that will convert binary to decimal. (I know there are thousands of these post already, but i still couldnt find the answers to my question :) .
question # 1:
How can i pervent people from entering numbers other than 1's and 0's ?
question #2:
For some reason when I enter the binary, Im only able to enter 5 digits or less, or else my program wront work.
For e.g. i enter 11011 :: the output will be 27
But when i enter 111101 :: the output will be 0
Code:
#include <stdio.h>
#include <conio.h>
int array[1000];
int getbinary(int binary);
main()
{
int temp;
int binary;
int power;
int decimal;
int cell;
cell = 0;
power = 1;
decimal = 0;
binary = getbinary(binary);
do{
temp = binary % 2;
if (temp==1)
{
array[cell] = power;
}
else
{
array[cell] = 0;
}
cell++;
power = power * 2;
binary = binary * .1;
} while(binary > 0);
for (cell=cell; cell>=0; cell--)
{
decimal = array[cell] + decimal;
}
printf("%d decimal\n", decimal);
getch();
}
int getbinary(int binary)
{
printf("Please enter binary: ");
scanf("%d", &binary);
return binary;
}
Thx!!
-
answ to 1 (i Think. I am a newbie too.. so :) )
Code:
int num;
scanf("%d", &num);
while((num != 0) || (num !=1)){
printf("\n please print 0 or 1 :");
scanf("%d",&num);
}
try this...
-
-
-
to swagatob : hehe, where do i put that code?? I try to put it in the getbinary functions, but when I run it, the program will just keep on asking me to enter please print 0 or 1 no matter wut i enter.
-
Code:
while((num != 0) && (num !=1)){
printf("\n please print 0 or 1 :");
scanf("%d",&num);
}
as you can see that I am a newbee too :p
EDIT: while loop changed.. it possibly should be and not or
-
for 2 maybe use long rather than int... I am not sure though.....
-
thx swagatob, i think i almost got it to work
edit:
oops, lol i dont know wut happen but it dont work again.
ill follow ur direction again swagatob, and im not sure is this wut u wanted me to do?
Code:
#include <stdio.h>
#include <conio.h>
int array[1000];
int getbinary(int binary);
main()
{
int temp;
int binary;
int power;
int decimal;
int cell;
cell = 0;
power = 1;
decimal = 0;
binary = getbinary(binary);
do{
temp = binary % 2;
if (temp==1)
{
array[cell] = power;
}
else
{
array[cell] = 0;
}
cell++;
power = power * 2;
binary = binary * .1;
} while(binary > 0);
for (cell=cell; cell>=0; cell--)
{
decimal = array[cell] + decimal;
}
printf("%d decimal\n", decimal);
getch();
}
int getbinary(int binary)
{
printf("Please enter binary: ");
scanf("%d", &binary);
while((binary != 0) && (binary != 1))
{
printf("Please enter binary 0's or 1's: ");
scanf("%d", &binary);
}
return binary;
}
-
hi
any more suggestion?
ary would be appeciated
-
suggestion for
swagatob:
use your edit button instead of posting new ones