某次的作业需要我们做10进制到2进制/8进制的转换为了偷懒就随手谢了下面的东西.
#include
using namespace std;
int main()
{
const int BASE = 2;
unsigned long num = 0;
int binaryNum[64] = {0};
cout << "Enter a number: ";
cin >> num;
if(!cin.fail() && num > 0)
{
int numMod = 0, length = 0;
while(num != 0)
{
numMod = num % BASE;
binaryNum[length++] = numMod;
cout << num << " / " << BASE << " = " <<
num / BASE << " + " << numMod << endl;
num /= BASE;
}
cout << endl << "Length: " << length << endl;
cout << "Result: ";
for(int i = length-1; i >= 0; i--)
cout << binaryNum[i];
cout << endl;
}
else
cerr << "Wrong Input.\n";
return 0;
}