前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >任意进制转换

任意进制转换

作者头像
川川菜鸟
发布2021-10-18 16:32:26
2690
发布2021-10-18 16:32:26
举报
代码语言:javascript
复制
//群:970353786
#include "stdio.h"
#include
using namespace std;
#define StackSize 100
typedef char ElemType;
typedef struct
{
    ElemType data[StackSize];
    int top;
}SqStack;
int trans(int d, int b, char string[])  //string用于存放转换后的字符串
{
    SqStack st;
    char ch;
    int r, i = 0;
    st.top = -1;      // 栈初始化
    if (b <= 1 || b > 36 || b == 10)  // 2≤b≤36且不为10
    {
        printf_s(" b is Error\n"); return 0;
    }
    while (d != 0)//辗转相除法
    {
        r = d % b; //求余数
        ch = r + (r < 10 ? '0' : 'A' - 10);  // 将余数转换为相应的字符
        st.top++;  st.data[st.top] = ch;   // 进栈
        d /= b;
    }
    while (st.top != -1)
    {
        string[i++] = st.data[st.top];   //将出栈的字符放入字符数组string
        st.top--;
    }
    string[i] = '\0';     //加入字符串结束标志
    return  1;
}
void main()
{
    while (1)
    {
        char str[10];
        int d, b, t;
        printf_s("请输入整数:");   //请输入待转换的整数
        scanf_s("%d", &d);
        printf("请输入要转换为几进制:"); // 请输入待转换的进制
        scanf_s("%d", &b);
        t = trans(d, b, str);          // 调用进制转换函数
        cout << "进制转换结果为:";
        if (t == 0) printf("Error!");
        else printf("%s\n", str);      // 输出转换结果字符串
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-05-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档