G
N
I
D
A
O
L

【算法设计-模拟】进制转换

1. 十进制转二进制

#include <stdio.h>
#include <vector>
using namespace std;

int main(){
	unsigned int n;
	
	while (scanf("%d", &n) != EOF){
		vector<int> binary; // 写在里面,每次循环都会被清空
		
		while (n != 0){
			binary.push_back(n % 2);
			n = n / 2;
		}
		
		for (int i = binary.size() - 1; i >= 0; i--){
			printf("%d", binary[i]);
		}
		printf("\n");
	}
	
	return 0;
}

2. 十进制转r进制(2<=r<=36)

#include <stdio.h>
#include <vector>
using namespace std;

int main(){
	int num, r;
	int tmp;
	
	printf("请输入数字num以及r进制:\n");
	
	while (scanf("%d %d", &num, &r) != EOF){
		vector<char> result;
		tmp = 0;
		
		while (num > 0){
			tmp = num % r;
			if (tmp < 10)
				result.push_back(tmp + '0');
			else
				result.push_back(tmp - 10 + 'A');
			num = num / r;
		}
		
		for (int i = result.size() - 1; i >= 0; i--){
			printf("%c", result[i]);
		}
		printf("\n");
	}
	
	return 0;
}

3. 将M进制数X转换为N进制数(2<=M, N<=36)

#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main(){
	int M, N;
	string X;
	int tmp, num;
	
	printf("请输入M以及N,和M进制下的数字X:\n");
	
	while (cin >> M >> N >> X){
		vector<char> result;
		num = 0;
		
		// 先将M进制数转换为十进制数
		for (int i = 0; i < X.size(); i++){
			if (i == 0)  // 计算M^i
				tmp = 1;
			else
				tmp = M * tmp;
				
			int index = X.size() - i - 1;
			if ('0' <= X[index] && X[index] <= '9')
				num += (X[index] -'0') * tmp;
			else if ('A' <= X[index] && X[index] <= 'Z')
				num += (X[index] -'A' + 10) * tmp;
			else if ('a' <= X[index] && X[index] <= 'z')
				num += (X[index] -'a' + 10) * tmp;
		}
		
		//printf("%d\n", num);
		
		// 再将十进制数转换为N进制数 
		while (num > 0){
			tmp = num % N;
			if (tmp < 10)
				result.push_back(tmp + '0');
			else
				result.push_back(tmp - 10 + 'A');
			num = num / N;
		}
		
		for (int i = result.size() - 1; i >= 0; i--)
			printf("%c", result[i]);
		printf("\n");
	}
	
	return 0;
}
posted @ 2023-03-03 11:01  漫舞八月(Mount256)  阅读(15)  评论(0编辑  收藏  举报