c++怎样编写将16进制的数转为10进制的数
答案:4 悬赏:40
解决时间 2021-03-21 01:26
- 提问者网友:✐ۖ﹏ℳ๓北风
- 2021-03-20 21:29
c++怎样编写将16进制的数转为10进制的数……用函数怎么编写?16进制是随便输入的,用函数调用编写
最佳答案
- 二级知识专家网友:抱不住太阳的深海
- 2021-03-20 22:47
#include<iostream.h>
#include<string.h>
#include<math.h>
void change(char *nu)
{
int i,l,j,sum=0;
l=strlen(nu);
for(i=l-1,j=0;i>=0;i--,j++)
{
if(nu[i]>='0'&&nu[i]<='9')
sum+=(nu[i]-48)*pow(16,j);
if(nu[i]>='a'&&nu[i]<='f')
sum+=(nu[i]-87)*pow(16,j);
if(nu[i]>='A'&&nu[i]<='F')
sum+=(nu[i]-55)*pow(16,j);
}
cout<<"转为十进制数为:"<<sum<<endl;
}
void main()
{
char num[10];
cin>>num;
cout<<"十六进制数:"<<num<<endl;
change(num);
}
#include<string.h>
#include<math.h>
void change(char *nu)
{
int i,l,j,sum=0;
l=strlen(nu);
for(i=l-1,j=0;i>=0;i--,j++)
{
if(nu[i]>='0'&&nu[i]<='9')
sum+=(nu[i]-48)*pow(16,j);
if(nu[i]>='a'&&nu[i]<='f')
sum+=(nu[i]-87)*pow(16,j);
if(nu[i]>='A'&&nu[i]<='F')
sum+=(nu[i]-55)*pow(16,j);
}
cout<<"转为十进制数为:"<<sum<<endl;
}
void main()
{
char num[10];
cin>>num;
cout<<"十六进制数:"<<num<<endl;
change(num);
}
全部回答
- 1楼网友:陪我到地狱流浪
- 2021-03-21 02:07
#include <iostream>
using namespace std;
#define MAX_NUM 100
int q(int n) ////////////求权
{
int result(1);
if(n==0)
return 1;
else
{
for(int i=0;i<n;i++)
{
result*=16;
}
return result;
}
}
int translate(char* c)
{
int result(0),tmp(0);
int count(0);
for(int i=0;c[i]!='\0';i++)
count=i;
for(int i=0;i<count+1;i++)
{
if(c[i]>='0' && c[i]<='9')
result+=(int(c[i])-48)*q(count-i);
else if(c[i]>='a' && c[i]<='f')
result+=(int(c[i])-87)*q(count-i);
else if(c[i]>='A' && c[i]<='F')
result+=(int(c[i])-55)*q(count-i);
else
return -1;
}
return result;
}
int main()
{
char a[100]={' '};
cin>>a;
cout<<translate(a)<<endl;
}
- 2楼网友:不傲怎称霸
- 2021-03-21 01:03
在机器中所有数据都是十六进制形式的.
printf sprintf 这两个函数提供此类型的转换.
建议楼主查看这两个函数的用法.
- 3楼网友:懂得ㄋ、沉默
- 2021-03-21 00:06
建议用栈来处理
我曾经做过八进制转十进制的,你可以参考一下:
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define STACK_INIT_SIZE 100
#define OVERFLOW -2
#define STACKINCREMENT 10
#define ERROR 0
typedef int status;
typedef int elemtype;
typedef struct
{
elemtype *base;
elemtype *top;
int stacksize;
}SqStack;
status InitStack(SqStack *S)
{
S->base=(elemtype*)malloc(STACK_INIT_SIZE*sizeof(elemtype));
if(!S->base) return OVERFLOW;
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
return OK;
}
status push(SqStack *S,elemtype e)
{
if(S->top-S->base>=S->stacksize)
{
S->base=(elemtype*)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(elemtype));
if(!S->base)return OVERFLOW;
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*S->top++=e;
//printf("%d ",*(S->top-1));
return OK;
}
status pop(SqStack *S,elemtype *e)
{
if(S->top==S->base) return ERROR;
*e=*--S->top;
return OK;
}
void main()
{
SqStack S;
elemtype n;
elemtype e;
InitStack(&S);
printf("请输入要转换的十进制数:");
scanf("%d",&n);
while(n)
{
push(&S,n%8);
n=n/8;
}
printf("\n");
printf("转换后的八进制数:");
while(S.base!=S.top)
{
pop(&S,&e);
printf("%d",e);
}
printf("\n");
}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯