本文目錄一覽:
C語言十進位轉八進位
現在我一共給你三個答案:
1遞歸的,
2你原先改成的,
3一般的
**********************************************************************
/*如你所願寫個遞歸的*/
#includestdio.h
r8(int a)
{
int i,j;
if(a==0)
return (0);
else
{
j=a%8;
i=a/8;
r8(i);
printf(“%d”,j);
}
}
int main()
{
int n;
printf(“請輸入十進位數:”);
scanf(“%d”,n);
printf(“轉換成八進位數是:”);
r8(n);
printf(“\n”);
}
**********************************************************************
原先代碼修改的:
#include “stdio.h”
#include “math.h”
main()
{
int i,n=0,o=0,j=0;
scanf(“%d”,i); /*改成*/
if(i=7)
o=i;
else
{
while(i7)
{ /*加括弧*/
j=i%8;
i=i/8;
o=j*pow(10,n)+o;
n++;
} /*加括弧*/
}
o=o+i*pow(10,n);
printf(“o=%d\n”,o);
}
**********************************************************************
另外,轉八進位可以這樣寫
#include “stdio.h”
int main()
{
int d;
printf(“請輸入十進位數:”);
scanf(“%d”,d);
printf(“該數的八進位表示為:%o\n”,d);
return 0;
}
c語言「把十進位數轉換成八進位數」怎麼寫
#includestdio.h
#includestring.h
main()
{
int i,m,n,s=0,t=1;char a[100],b[100];
gets(a);//用回車分割
scanf(“%d%d”,n,m); //輸入的進位和想要轉換的進位
for(i=strlen(a)-1;i=0;i–)//先轉10進位
{ if(n!=16)
s+=(a[i]-48)*t;
else
s+=(a[i]-55)*t;
t*=n;
}
for(i=0;s;i++)//10進位轉你想要的進位
{
if(s%m=10)
b[i]=s%m+55;
else
b[i]=s%m+48;
s/=m;
}
b[i]=’\0′;
for(i=strlen(b)-1;i=0;i–)
printf(“%c”,b[i]);
}
這是任意進位的轉換 望滿意
C語言 十進位數轉換八進位 演算法
方法一:直接使用控制字元串 %o 八進位%x
方法二:
求余來算,比如求十進位數 x(x100) 的8進位,先通過 x%8 可以得到個位(末位)上的數,當十進位數等於8時,必然會進位,求余的結果正好是不能進位的部分,x=x/8(這就像位移,x的8進位數向右移了一位),這樣已經求出來的 個位 位移後沒有了,原來的十位變成了個位,繼續把得到的x按上面的方式求末位,就能求出來十位,按照這種方式得到的 8進位數 是反的(先得到個位,再十位。。。),這樣很適合放到棧中,取得時候又會反過來,偽代碼可以這樣寫:
while(x){
printf(“%d”,x%n);//會列印出x轉換為 N進位數 從低位到高位上的每一位數
x/=n;
}
十進位轉換N進位:
#includestdio.h
#includestdlib.h
#includestring.h
typedef int INT;
typedef struct dd
{
INT data;
struct dd *next;
}LNode,*LStack;
LStack pushstack(LStack top,int x)
{
LStack p;
p=(LStack)malloc(sizeof(LNode));
if((x)!=-1) {p-data=(x); p-next=top; top=p;}
return top;
}
LStack outstack(LStack top,int *x)
{
LStack p=top;
*x=p-data;
top=p-next;
free(p);
return top;
}
main()
{
int x,n;
LStack top=NULL;
printf(“請輸入原數及要轉換的進位:”);
do{
scanf(“%d%d”,x,n); //輸入一個十進位數和要轉換的進位,比如3 2 得到1 }while(x35||x0||n2);
while(x){ //這個循環把每一位放到棧中
top=pushstack(top,x%n);
x/=n;
while(top!=NULL)
{
top=outstack(top,x);
if(x10)
printf(“%c”,x+’0′);
else
printf(“%c”,x+’A’-10);
}
return 0; }
用c語言的函數調用如何將一個十進位數轉換為八進位數?
10進位轉換8進位輸出,使用printf函數的格式輸出%o即可。如果需要得到轉換後的字元串,使用sprintf函數即可。
常式:
#include stdio.h
int main (){
int x;
char s[100];
printf(“輸入要轉換的十進位數:\n”);
scanf(“%d”,x);
sprintf(s,”%o”,x); //十進位轉換為八進位,並保存到s字元串當中
printf(“使用sprintf函數轉換的八進位數是:%s\n”,s)
printf(“使用printf函數轉換的八進位數是:%o\n”,x); //十進位轉換為八進位,並直接輸出到屏幕
return 0;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/242791.html