二进制数与十进制数的相互转换

二进制到十进制

//迭代法将二进制数转化为十进制数
#include<iostream>
#include<cmath>
using namespace std;
void binToDec(int binaryNumber, int& decimal, int& weight);
int main()
{
	int decimalNum;
	int bitWeight;
	int binaryNum;
	decimalNum = 0;
	bitWeight = 0;
	cout << "Enter a number in binary:";
	cin >> binaryNum;
	cout << endl;
	binToDec(binaryNum, decimalNum, bitWeight);
	cout << "Binary " << binaryNum << " = " << decimalNum << " decimal" << endl;
	return 0;
}
void binToDec(int binaryNumber, int& decimal, int& weight)
{
	int bit;
	if (binaryNumber > 0)
	{
		bit = binaryNumber % 10;
		decimal = decimal + bit*static_cast<int>(pow(2, weight));
		binaryNumber = binaryNumber / 10;
		weight++;
		binToDec(binaryNumber, decimal, weight);
	}
}

十进制转二进制

//迭代法将十进制数转化为二进制数
#include<iostream>
using namespace std;
void decToBin(int num, int base);
int main()
{
	int decimalNum;
	int base;
	base=2;
	cout << "Enter a number in decimal: ";
	cin >> decimalNum;
	cout << endl;
	cout << "Decimal " << decimalNum << " = ";
	decToBin(decimalNum, base);
	cout << " binary" << endl;
	return 0;
}
void decToBin(int num, int base)
{
	if (num > 0)
	{
		decToBin(num / base, base);
		cout << num%base;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42020563/article/details/80309414