1. Konversi bilangan desimal ke bilangan biner
//Sabam Parjuangan
//Decimal to Binary Convert
#include
void dec2bin(long decimal, char *binary);
int main()
{
long decimal;
char binary[80];
printf("\n\n Enter an integer value : ");
scanf("%ld",&decimal);
dec2bin(decimal,binary);
printf("\n The binary value of %ld is %s \n",decimal,binary);
getchar(); // trap enter
getchar(); // wait
return 0;
}
void dec2bin(long decimal, char *binary)
{
int k = 0, n = 0;
int neg_flag = 0;
int remain;
int old_decimal; // for test
char temp[80];
// take care of negative input
if (decimal < 0) { decimal = -decimal; neg_flag = 1; } do { old_decimal = decimal; // for test remain = decimal % 2; // whittle down the decimal number decimal = decimal / 2; // this is a test to show the action printf("%d/2 = %d remainder = %d\n", old_decimal, decimal, remain); // converts digit 0 or 1 to character '0' or '1' temp[k++] = remain + '0'; } while (decimal > 0);
if (neg_flag)
temp[k++] = '-'; // add - sign
else
temp[k++] = ' '; // space
// reverse the spelling
while (k >= 0)
binary[n++] = temp[--k];
binary[n-1] = 0; // end with NULL
}
2. Konversi Bilangan Biner ke Desimal
//Sabam Parjuangan
//Binary to dec convert
#include
#include
#include
int main(void) {
int dec=0,flag=0.0;
int bin, bit;
double exp=0.0;
printf("Enter Binary Number 0 or 1 : ");
scanf("%d", &bin);
while(bin) {
bit=bin%10;
if (bit !=0 && bit !=1) {
flag=1;
}
bin=bin/10;
dec=dec+bit*pow(2, exp);
exp++;
}
if(flag) {printf("It's not binary number\n");
printf("Please try again! \n");}
else {printf("Decimal value is : %d\n", dec);}
return 0;
}
Ingat ini di coba menggunakan turbo c++, tujuan aplikasi ini untuk mengkonversi bilangan biner ke desimal dan sebaliknya, yang menggunakan fungsi IF-ELSE
Selamat mencoba!
No comments:
Post a Comment