C语言程序怎么把十进制的数转换成八进制的数?

Python018

C语言程序怎么把十进制的数转换成八进制的数?,第1张

C语言程序十进制的数转换成八进制的数的办法:

#include <stdio.h>

#include <math.h>

void main()

{

int n,a,sum = 0,i =0

printf("十进制输出一个数n\n")

scanf("%d",&n)

while(n)

{

a = n%8

n = n/8

sum += a*pow(10,i)

i++

}

printf("八进制输出sum:%d",sum)

}

如果输入是十进制字符,输出是八进制字符串,则用如下dec2oct函数可实现转换

#include<stdio.h>

int dec2oct(char *dec,char *oct){

    int num=0,i=0,t

    char c

    do{

        c=*dec

        if(!c) return 0  // 出错了,没找到10进制数

        if(c>='0' && c<='9') break // 找到十进制数了

        else    dec++

    }while(1)

    do{

        num = num*10 + (c-'0')

        c=*++dec

        if(!c) break   // 没有其他字符了

        if(c>='0' && c<='9') continue   // 还有十进制字符,继续

        else break    // 没有其他十进制字符了,退出

    }while(1)

    do{

        t = num % 8

        oct[i] = t+'0'

        num = num / 8

        if(num==0) break

        i++

    }while(1)

    for(t = (i+1)/2t<=it++){

        num = oct[t]

        oct[t] = oct[i-t]

        oct[i-t]=num

    }

    oct[i+1]='\0'

    return 1

}

int main()

{

    char dec[20],oct[20]

    while(scanf("%s",dec)==1)

        if(dec2oct(dec,oct)) printf("%s\n",oct)

        else break

    return 1

}

该函数dec2oct先将输入字符串中的 10进制字符串转换成二进制数存下来,然后再将二进制数转换成八进制字符串。