永发信息网

c语言编程 从键盘输入一个十进制正整数,将其转换成二至十六任意进制的数字字符串

答案:2  悬赏:0  手机版
解决时间 2021-03-29 19:41
  • 提问者网友:人生佛魔见
  • 2021-03-28 18:49
c语言编程 从键盘输入一个十进制正整数,将其转换成二至十六任意进制的数字字符串
最佳答案
  • 五星知识达人网友:孤独的牧羊人
  • 2021-03-28 19:49
#include
void convert(unsigned int in, unsigned int type, char *out) {
int i=0, n;
char temp;
while (in > 0) {
n = in % type;
if(n<10){
out[i] = n + '0';
}
else {
out[i] = n-10 + 'A';
}
i++;
in = in / type;
}
out[i] = 0;
if (i == 0) {
out[0] = '0';
out[1] = 0;
}
else {
for (n = 0; n < i/2; n++) {
temp = out[n];
out[n]=out[i - n - 1];
out[i - n - 1] = temp;
}
}
}
int main()
{
unsigned int d;
char t[33];
scanf_s("%u", &d);
convert(d, 2, t);
printf("二进制:%s\n", t);
convert(d, 8, t);
printf("八进制:%s\n", t);
convert(d, 16, t);
printf("十六进制:%s\n", t);
return 0;
}
全部回答
  • 1楼网友:迟山
  • 2021-03-28 20:42
// asdf.cpp : Defines the entry point for the console application.
//
#include "stdio.h"
void _10ton(int x, char *des, int n) //将十进制数x转化为n进制, 结果存于des
{ int i=0, j=0;
char t;

if(n<10)
{ while( x>0 )
{ des[i] = x%n + '0';
i++;
x = x/n;
}
}
else
{ while( x>0 )
{ int tx=x%n;
if(tx<10)
des[i] = tx + '0';
else
des[i] = tx-10+'A';
i++;
x = x/n;
}
}

i--;
for(j=0; j { t = des[i];
des[i] = des[j];
des[j] = t;
}
}
int main(int argc, char* argv[])
{
int x = 28; //十进制数
int n = 14; //转为16进制
char str[81]={'\0'};
_10ton(x, str, n);
printf("%s", str);
return 0;
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯