用C++写一个进制转换的代码
时间: 2023-03-14 12:08:46 浏览: 53
以下是一个简单的进制转换代码:#include <stdio.h>int main()
{
int i, n; // 定义变量
printf("请输入要转换的数:");
scanf("%d", &n); // 读取要转换的数
printf("十进制转换后的结果:");
for (i=31; i>=0; i--) // 循环语句
{
printf("%d", (n>>i)&1); // 将n右移i位与1进行按位与运算,然后输出
}
printf("\n");
return 0;
}
相关问题
用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;
}
```
如果您有关于代码的任何问题,请随时问我!