用C++写一个进制转换的代码
时间: 2023-03-28 20:04:45 浏览: 122
好的,以下是一个简单的进制转换代码示例:
```c
#include <stdio.h>
int main() {
int num, base;
printf("请输入一个十进制数:");
scanf("%d", &num);
printf("请输入要转换的进制:");
scanf("%d", &base);
int result[32], i = ;
while (num > ) {
result[i++] = num % base;
num /= base;
}
printf("转换后的结果为:");
for (int j = i - 1; j >= ; j--) {
if (result[j] < 10) {
printf("%d", result[j]);
} else {
printf("%c", 'A' + result[j] - 10);
}
}
printf("\n");
return ;
}
```
以上是一个简单的进制转换代码,可以将一个十进制数转换为任意进制的数。
相关问题
用c++写一个进制转换代码
好的,以下是C++写的一个进制转换代码,可以将10进制转换成2-16进制。
#include<iostream>
#include<stack>
using namespace std;
int main(){
int n, r;
stack<char> s; //定义栈,用于存放余数
cout<<"请输入一个十进制数:";
cin>>n;
cout<<"请输入需要转换的进制(2-16):";
cin>>r;
while(n){
int t = n % r; //计算余数
if(t < 10){
s.push(t + '0'); //如果余数是0-9,将其转换成字符存入栈中
}
else{
s.push(t - 10 + 'A'); //如果余数是10-15,将其转换成对应的字符存入栈中
}
n /= r; //除以进制数,计算下一个余数
}
cout<<"转换结果:";
while(!s.empty()){ //循环输出栈中的字符,实现倒序输出
cout<<s.top();
s.pop();
}
cout<<endl;
return 0;
}
请用c++写一段进制转换代码
Sure, 进制转换代码如下:
```c
#include <stdio.h>
void convert(int num, int base) {
int rem = num % base;
if (num == 0) {
return;
} else {
convert(num / base, base);
if (rem < 10) {
printf("%d", rem);
} else {
printf("%c", rem - 10 + 'A');
}
}
}
int main() {
int num, base;
printf("Enter a decimal number: ");
scanf("%d", &num);
printf("Enter the base to convert to (2-16): ");
scanf("%d", &base);
if (base < 2 || base > 16) {
printf("Invalid input\n");
} else {
printf("%d base 10 = ", num);
convert(num, base);
printf(" base %d\n", base);
}
return 0;
}
```
如果您有关于代码的任何问题,请随时问我!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)