0%

八进制转换十进制

文章时效性提示

本文发布于 492 天前,部分信息可能已经改变,请注意甄别。

题目:八进制转换为十进制

例如,八进制数1507转换为十进制数的计算过程如下:‌
个位‌:7乘以8的0次方,即7 * 8^0 = 7。
十位‌:0乘以8的1次方,即0 * 8^1 = 0。
‌百位‌:5乘以8的2次方,即5 * 8^2 = 320。
‌千位‌:1乘以8的3次方,即1 * 8^3 = 512。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stdio.h>
int Cal_Decimal(int input)
{
    int sum = 0;
    while (input!=0)
    {
        int temp = input;
        if (temp < 10)//十进制的数字除到了10以下,直接加上这个数字
        {
            sum = sum + temp;
            break;
        }
        int capacity = 0;//数字的位数
        int temp_capacity;//临时变量-数字的位数
        int a = 10;//用于计算最高位的值
        int i = 0;
        int j = 0;
        int x = 8;//从高位往低位得到各位的数字
        while (temp != 0)//先计算位数
        {
            temp = temp / 10;
            capacity++;
        }
        capacity = capacity - 1;
        temp_capacity = capacity;
        temp = input;
        while (temp_capacity != 0)//获得现在最高位的数字
        {
            temp = temp / 10;
            temp_capacity--;
        }
        j = temp;
        temp_capacity = capacity;
        while (temp_capacity > 1)//计算乘以8的次方数
        {
            x = x * 8;
            temp_capacity--;
        }
        while (capacity >1) //减去最大的一位
        {
            a = a * 10;
            capacity--;
        }
        a = a * j;
        i = x * j;
        input = input - a;
        sum = sum + i;
    }
    return sum;
}
int main() {
    int input;
    int output;
    printf("请输入一个数字:->");
    scanf("%d",&input);
    output = Cal_Decimal(input);
    printf("%d",output);
    return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
int main (void)
{
    char s[20] = "1507";
    int i = 0;
    int n = 0;
    while(s[i]!='\0')
    {
        n = n * 8 + s[i] - '0';
        i++;
    }
    printf("%d",n);
    return 0;
}