摘自老師實驗代碼參考
【實驗2】 16進制轉換
設計程序,輸入一個十進制數N(0≤N≤2147483647),輸出相應的十六進制數。
1.輸入描述
現在給你多組測試案例。第一行是一個正整數,表示接下來的測試案例的個數。每個測試案例是一行,只有一個整數。
2.輸出描述
每個測試案例都打印在一行上。
3.樣例輸入
5
2013
0
10000
1
2147483647
方法一:采用vector

#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

#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; }
方法三:

#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; }