[C++]10进制转换二进制(带计算过程)

某次的作业需要我们做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;
}

效果图:
20131106214952

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注


此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据