❶ c語言: 輸入一個十進制正整數,將其轉換成八進制數,並輸出結果。
個人意見,僅供參考!
1.
//用轉意字元
⑴這是輸出有前綴「0」的八進制數
int
main(void)
{
int
a;
printf("\n");
scanf("%d",&a);
printf("%#o",a);
/*"%#o"這里的「#」就是輸出前綴的,「o」是八進制*/
getch();
return
0;
}
⑵輸出無前綴的八進制數
main()
{
int
a;
printf("\n");
scanf("%d",&a);
printf("%o",a);
/*不要在o前加「#」*/
}
——————————————————————————————
2.
//用數據結構的知識解決
int
*Init()
{
int
*top,*base;
base=(int
*)malloc(sizeof(int)
*
50);
if(!base)
{printf("Error!");exit();}
top=base;
return
top;
}
int
*push(int
*top,int
n)
{
*top=n;
top++;
return
top;
}
int
pop(int
*top)
{
int
e;
top--;
e=*top;
return
e;
}
void
convs()
{
int
*top,
*base;
int
e,N;
int
i;
top=Init();
base=top;
printf("Input
the
number:\n");
scanf("%d",&N);
while(N!=0)
{
top=push(top,N%8);
N=N/8;
}
printf("After
change,the
number
is:\n");
while(top!=base)
{
e=pop(top);
top--;
printf("%d",e);
}
printf("\n");
}
main()
{
convs();
getch();
}
❷ 用C語言進行十進制和八進制的轉換怎麼做
如果輸入是十進制字元串,輸出是八進制字元串,則用如下dec2oct函數可實現轉換
#include<stdio.h>
intdec2oct(char*dec,char*oct){
intnum=0,i=0,t;
charc;
do{
c=*dec;
if(!c)return0;//出錯了,沒找到10進制數
if(c>='0'&&c<='9')break;//找到十進制數了
elsedec++;
}while(1);
do{
num=num*10+(c-'0');
c=*++dec;
if(!c)break;//沒有其他字元了
if(c>='0'&&c<='9')continue;//還有十進制字元,繼續
elsebreak;//沒有其他十進制字元了,退出
}while(1);
do{
t=num%8;
oct[i]=t+'0';
num=num/8;
if(num==0)break;
i++;
}while(1);
for(t=(i+1)/2;t<=i;t++){
num=oct[t];
oct[t]=oct[i-t];
oct[i-t]=num;
}
oct[i+1]='