Yêu cầu:
Chuyển từ số nhị phân sang thập phân.
Giải thuật:
– Để chuyển từ số nhị phân sang thập phân. Chúng ta dùng công thức sau:
bnbn-1..b0 = bn.2n + bn-1.2n-1 + ...+ b0.20
Code:
/************************************************************ * Author: VNCODING * History * 2015/11/02 first create VNCODING *************************************************************/ #include "stdio.h" #include "conio.h" void main() { int num, binary_val, decimal_val = 0, base = 1, rem; printf("\nNhap so nhi phan(1 & 0): "); scanf("%d", &num); /* maximum five digits */ binary_val = num; while (num > 0) { rem = num % 10; decimal_val = decimal_val + rem * base; num = num / 10 ; base = base * 2; } printf("So nhi phan = %d \n", binary_val); printf("Gia tri he thap phan = %d \n", decimal_val); getch(); }
Kết quả:
Nhap so nhi phan(1 & 0): 111011 So nhi phan = 111011 Gia tri he thap phan = 59
Leave a Reply
You must be logged in to post a comment.