岳州窑青瓷茶具:用C编写十进制数转换八进制程序

来源:百度文库 编辑:神马品牌网 时间:2024/04/27 20:13:26

将十进制数转化成八进制数

int * InitStack() //初始化栈
{
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 conversion()
{
int * top, * base;
int e,N;
int i;
top=InitStack();
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()
{
conversion();
}

大家说的都对,如果是初学者呢
就这样实现:
1.这是输出的八进制要前缀“0”的话……
int main(void)
{
int a;
printf("\n");
scanf("%d",&a);
printf("%#o",a); /*"%#o"这里的“#”就是输出前缀的,“o”是八进制*/
getch();
return 0;
}
2.如果是输出无前缀的八进制数的话,用楼上的就可以了
main()
{
int a;
printf("\n");
scanf("%d",&a);
printf("%o",a); /*不要在o前加“#”*/
}
上面的方法同样适合与十六进制的转换不过要把“o”变为“x”
至于四楼的“栈”的方法,能很好的帮助你了解数据结构、各种进制的转换原理,不过等你学了函数、指针以后再看就明白了……^_^

#include <stdio.h>
#define BASE 8 /*要转换成几进制数/*
#define DIGIT 100 /*转换数的位数/*
int main(void)
{
int i,input;
int x[DIGIT];
printf("Please enter(Enter q to quit)")
while(scanf("%d",&input)==1)
{
for (i=0;input!=0;input/=BASE)
x[i]%=input;
for (;i<0;i--)
printf("%d",x[i]);
}
return 0;
}

main(){
int a;
scanf("%d",&a);
printf("%o",a);
}
问题解决。

不过要是标准的数据结构方法应该是楼上那个用栈的。
还可以实现任意进制的转换。

偶新手,别见笑:
//C++:

#include<iostream>
using namespace std;
void main(){
int a[1024],n,i=0,b[1024];
cin>>n;

a[i]=n/8;
b[i]=n%8;
g:
if(a[i]>8){
i++;
a[i]=a[i-1]/8;
b[i]=a[i-1]%8;
goto g;
}

cout<<a[i];
while(i>=0)
{
cout<<b[i];
i--;

}
}

用写吗,用%o输出的话就是8进制。

比如printf("%o",123)。就是把123转换为8进制输出出来。