本文 首发于 🌱 煎茶转载 请注明 来源

题目来源

时间限制:C/C++ 1秒,其他语言2秒空间限制:C/C++ 32M,其他语言64M

题目描述

写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。(多组同时输入 )

输入描述

输入一个十六进制的数值字符串。

输出描述

输出该数值的十进制字符串。

示例1 输入 0xA 输出 10

参考代码

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

//C语言版本:
#include <stdio.h>
int main(){
    int a;
    while (scanf("%x", &a) != EOF){
        printf("%d\n", a);
    }
    return 0;
}
 
//C++版本:
#include <iostream>
int main(){
    int a;
    while ((cin >> hex >> a)){
        cout << a << endl;}   
    }
   return 0;
}

已上代码为技巧作答,如果是直接算,可采用下面这种:


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

#include <iostream>
using namespace std;
int main()
{
    char c;
    int s=0;
for(int i=1;i<=4;i++)
{
    cin>>c;
    if(c>=97 && c<=102) s=s*16+c-88+1;
    if(c>=65 && c<=70) s=s*16+c-56+1;
    if(c>=48 && c<=57) s=s*16+c-48;
}
cout<<s;
return 0;
}

技巧分析

  1. cin>>hex>>a,此时如果输入12,那么a就是ox12,也就是说此时的12是十六进制的,实际上a的值为18(十进制)。此时,如果用 cout<<a ;那么输出的是18.
  2. dec是十进制 如 cout<<dec<<b 就会把b转换成10进制再输出;hex 是16进制 如 cout<<dec<<b 就会把b转换成16进制再输出

参考文献