进制转换

任意进制转换:https://blog.csdn.net/The_Lich_King/article/details/37997229

十六进制转换为十进制

牛客网机试题:https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6?tpId=37&tqId=21228&rp=0&ru=/ta/huawei&qru=/ta/huawei/question-ranking

我的代码

#include <stdio.h>
#include <string.h>
#include <math.h>
void main()
{
    char str[100];
    int num;
    int len,n,i;
    while(gets(str))
    {
        num=0;
        len=strlen(str);
        n=len-2;
    
        for(i=2;i<len;i++)
        {
            if(str[i]>='0' && str[i]<='9')
                num+=pow(16,n-i+1)*(str[i]-48);
            else
            {
                if(str[i]=='A' || str[i]=='a')
                    num+=pow(16,n-i+1)*10;
                else if(str[i]=='B' || str[i]=='b')
                    num+=pow(16,n-i+1)*11;
                else if(str[i]=='C' || str[i]=='c')
                    num+=pow(16,n-i+1)*12;
                else if(str[i]=='D' || str[i]=='d')
                    num+=pow(16,n-i+1)*13;
                else if(str[i]=='E' || str[i]=='e')
                    num+=pow(16,n-i+1)*14;
                else if(str[i]=='F' || str[i]=='f')
                    num+=pow(16,n-i+1)*15;
            }
        }
        printf("%d",num);
    }
}

能通过代码

链接:https://www.nowcoder.com/questionTerminal/8f3df50d2b9043208c5eed283d1d4da6
来源:牛客网

#include<stdio.h>
#include<string.h>
#include<math.h>
int main()
{
    char str[100];
    int i=0,count,sum;
    while(gets(str))//用于多次输入
    {
        count=strlen(str);//计算字符串的长度
        sum=0;
        for(i=count-1;i>=0;i--)//从十六进制个位开始,每位都转换成十进制
        {
        if(str[i]>='0'&&str[i]<='9')//数字字符的转换
        {
            sum+=(str[i]-48)*pow(16,count-i-1);
        }
        else if(str[i]>='A'&&str[i]<='F')//字母字符的转换
        {
            sum+=(str[i]-55)*pow(16,count-i-1);
        }
        }
        printf("%d\n",sum);
    }
    return 0;
 }

我的代码为什么没有通过

最后发现是因为输出printf(“%d ”,num)处没有加换行符,加上后通过。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值