我知道用比如:984转十进制是 9*16^2+8*16+4
但是这个用函数不是太好写
请问还有别的算法吗?
怎么会难写,一个for循环就搞定了
[CODE]#include<stdio.h>
#include<string.h>
#define M 10
char s[M];
int len;
int power(int a,int b)//求a^b
{
int t=1,i;
for(i=1;i<=b;i++)
t*=a;
return t;
}
void dfs(int sum,int i)//递归
{
if(i==len)
{
printf("%d\n",sum);
return;
}
if(s[i]<='9')//数字是0——9
dfs(sum+(s[i]-48)*power(16,len-i-1),i+1);
else //数字是A--E
dfs(sum+(s[i]-55)*power(16,len-i-1),i+1);
return;
}
int main()
{
scanf("%s",s);//输入
len=strlen(s);
dfs(0,0);
return 0;
}[/CODE]
未验证,你试一下.
正好我前几天写了一个
用堆栈实现
#include<stdlib.h>
#include<stdio.h>
#define LEN sizeof(struct snode)
struct snode
{int data;
struct snode *next;
};
struct snode *stack=NULL;
void push(int value) //push a record to the top
{ struct snode *newp;
newp=(struct snode *)malloc(LEN);
newp->data=value;
newp->next=stack;
stack=newp;
}
void pop()
{struct snode *temp;
if(stack==NULL)
printf("The stack is empty\n");
else
{temp=stack;
stack=stack->next;
free(temp);
}
}
void Print_stack()
{struct snode *temp;
temp=stack;
while(temp!=NULL)
{
if(temp->data>=0&&temp->data<=9)
printf("%d",temp->data);
else
printf("%c",temp->data+87);
temp=temp->next;
}
}
main()
{long int num,temp;
int n;
printf("please input the number");
scanf("%d",&num);
printf("You want to converse the number to Bin or Octal or hex?");
printf("Bin :2\n");
printf("Octal:8\n");
printf("Hex :16\n");
scanf("%d",&n);
temp=num;
while(temp/n!=0)
{push(temp%n);
temp/=n;
}
printf("%d",temp);
Print_stack();
printf("\n");
}