摘自老师实验代码参考
【实验2】 16进制转换
设计程序,输入一个十进制数N(0≤N≤2147483647),输出相应的十六进制数。
1.输入描述
现在给你多组测试案例。第一行是一个正整数,表示接下来的测试案例的个数。每个测试案例是一行,只有一个整数。
2.输出描述
每个测试案例都打印在一行上。
3.样例输入
5
2013
0
10000
1
2147483647
方法一:采用vector
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <vector> using namespace std; int main() { int m, n; vector<int> v; char s[] = "0123456789ABCDEF";//字典 cin>>m; while(m--) { cin>>n; v.clear(); if (n == 0) v.push_back(0); while (n != 0) { v.push_back(n%16); n = n / 16; } vector<int>::reverse_iterator rit; for (rit = v.rbegin(); rit != v.rend(); rit++) cout<< s[*rit];//这里比较有技巧 cout<<"H" <<endl; } return 0; }
方法二:采用string
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { int m, n; string s; cin>>m; while(m--) { cin>>n; s = ""; if (n == 0) s = "0"; while (n != 0) { if (n%16 >9 ) s += n%16 - 10 +'A'; else s += n%16 + '0'; n = n / 16; } reverse(s.begin(), s.end());//反转 cout<<s <<"H" <<endl; } return 0; }
方法三:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <stdlib.h> #include <iostream> #include <algorithm> using namespace std; int main() { int m, n; char buf[80]; cin>>m; while(m--) { cin>>n; itoa(n, buf, 16);//转换为是小写16进制, transform(buf, buf + strlen(buf), buf, toupper);//转大写 cout<<buf <<"H" <<endl; } return 0; }