I expect someone will say this article is too simple again once I finish writing it... Without further ado: this week, our teacher gave our class a problem, which is how to convert a decimal number to binary. If you do it with math, it isn't hard. Just use short division and take the remainders.
How It Works
We can write the calculation out as a series of equations: (converting 10 from decimal to binary)
10/2=5...0
5/2=2...1
2/2=1...0
1/2=0...1
So the binary form of 10 is 1010
Following this calculation, we can write a do...loop. When the quotient is less than or equal to 0, the loop ends. Each time, we record the remainder and the quotient, use the quotient for the next division, and finally print the remainders "from bottom to top" to get the answer. This may be a little hard to follow in words, so take a look at the code~
VB Code:
VBScript download: Box.net|4Shared|Dropbox|Google
msgbox("此程式可幫你把十進位轉成二進位")
x=inputbox("請輸入一個數字") 'Get the number to convert
a=x
do while(a>0) 'Perform the division while a>0
q=a mod 2 & q 'Get the remainder. The key here is printing from bottom to top
a=a2 'Get the integer part for the next division
loop
msgbox(q) 'Output the resultC++ Code:
Code download: Box.net|4Shared|Dropbox|Google
#include
#include
using namespace std;
int main()
{
int x,y,;
cout«“Please input one number:”; cin»x;
cout«“result:"«endl;
y=x;
do{
cout«!(y % 2)«endl;
y=(int)y/2;
}while(y>0);
return 0;
}
