编写函数,该函数能完成任意的十进制数转换为 R(2≤R≤16)进制数。调用该函数,
将输入的一个十进制正整数分别转换为 R 进制数数字串。
方法一、
#include <iostream>
using namespace std;
void convert(int num, int a) {
int temp = num;
int len = 1;
//计算数字串长度
while (true) {
if (temp / a == 0) {
break;
}
else {
temp = temp / a;
len++;
}
}
int* arr = new int[len];
//计算转换结果
temp = num;
int result;
for (int i = 0; i < len; i++)
{
result = temp % a;
arr[i] = result;
temp = temp / a;
}
//输出
for (int i = len -1; i >= 0 ; i--)
{
cout << hex << arr[i];
}
}
int main() {
int num, a;
flag:
cout << "输入一个整数" << endl;
cin >> num;
cout << "转化进制数(2~16)" << endl;
cin >> a;
if (a < 2 || a>16) {
cout << "请输入有效信息" << endl;
goto flag;
}
else {
convert(num, a);
}
system("pause");
return 0;
}
方法二、
#include<iostream>
#include<string>
using namespace std;
int n, r, count;
void Aprint(int x)
{
if (x <= 9)
cout << x;
else {
char y = x - 10 + 'A';
cout << y;
}
}
void change(int n, int r)
{
if (n)
{
change(n / r, r);
Aprint( n%r);
}
}
int main()
{
cin >> n >> r;
change(n, r);
return 0;
}
博客介绍使用C++编写函数,实现将任意十进制数转换为2到16进制数。通过调用该函数,可将输入的十进制正整数转换为对应R进制数数字串,还提及了两种不同方法。
2453

被折叠的 条评论
为什么被折叠?



