7.八进制转十进制

#include <stdio.h>
int main()
{
    char *p,s[6];
    int n=0;
    p=s;
    printf("请输入你想转换的八进制数字:");
    gets(p);
    while(*(p)!='\0')
    {
        n=n*8+*p-'0';
        p++;
    }
    printf("他的十进制是:%d\n",n);
    return 0;
}
//输出结果为:
请输入你想转换的八进制数字:15
他的十进制是:13
Press any key to continue
 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是用链栈实现八进制转换十进制的代码实现,具体注释在代码中: ```c++ #include <iostream> #include <cmath> using namespace std; // 定义链栈结构体 struct Node { int data; Node* next; }; // 初始化链栈 void InitStack(Node*& S) { S = new Node; S->next = NULL; } // 判断链栈是否为空 bool StackEmpty(Node* S) { return S->next == NULL; } // 入栈 void Push(Node*& S, int x) { Node* p = new Node; p->data = x; p->next = S->next; S->next = p; } // 出栈 bool Pop(Node*& S, int& x) { if (StackEmpty(S)) { return false; } Node* p = S->next; x = p->data; S->next = p->next; delete p; return true; } // 读栈顶元素 bool GetTop(Node* S, int& x) { if (StackEmpty(S)) { return false; } x = S->next->data; return true; } // 八进制转换十进制 int OctToDec(char s[]) { Node* S = NULL; InitStack(S); int i = 0; while (s[i] != '\0') { Push(S, s[i] - '0'); // 将字符转换字并入栈 i++; } int dec = 0; int n = 0; int x; while (!StackEmpty(S)) { Pop(S, x); dec += x * pow(8, n); // 按计算 n++; } return dec; } int main() { char s[100]; cout << "输入一个八进制:"; cin >> s; int dec = OctToDec(s); cout << "转换十进制为:" << dec << endl; return 0; } ``` 这里使用了链栈来实现,具体的实现过程如下: 1. 从字符串的最后一开始遍历,将每一转换整数,并入栈。 2. 然后按照栈的后进先出的顺序,将每一字取出,并按照计算十进制值。 3. 最后得到的十进制值即为所求。 这里使用了 pow 函来计算 $8^n$,需要在头文件中添加 math.h。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值