生成代码: 十进制与任意进制转换
时间: 2023-06-12 14:02:21 浏览: 99
好的,请稍等,让我为您生成一段代码:
```
#include <iostream>
#include <string>
using namespace std;
string convertToBase(int num, int base) {
string digits = "0123456789ABCDEF";
string result = "";
while (num > 0) {
int digit = num % base;
result = digits[digit] + result;
num /= base;
}
return result;
}
int convertFromBase(string num, int base) {
int result = 0;
for (int i = 0; i < num.size(); i++) {
result = result * base + digits.find(num[i]);
}
return result;
}
int main() {
int num = 12345;
int base = 16;
cout << num << " in base 10 is " << convertToBase(num, base)
<< " in base " << base << endl;
string str = "2AF3";
base = 16;
cout << str << " in base " << base << " is " << convertFromBase(str, base)
<< " in base 10" << endl;
return 0;
}
```
这段程序可以实现将一个十进制数转换为任意进制数,以及将任意进制数转换为十进制数。您可以根据需要修改代码中的变量值。希望这可以帮到您!
阅读全文