#include <iostream> int hex(int n){ int temp; while(n != 0){ temp = n%16; if(temp >= 0 && temp <= 9) std::cout << temp << " "; else if(temp >= 10 && temp <= 15) std::cout << 'A' + temp - 10 << " "; n /= 16; }return temp; } int main() { hex(933); } 2 answers
Как вариант: #include <iostream> #include <vector> void hex(int n) { std::vector <int> v; while (n != 0) { v.push_back(n % 16); n /= 16; } for (int i = v.size() - 1; i >= 0; --i) { if (v[i] > 9) std::cout << (char)((int)'A' - (10 - v[i])); else std::cout << v[i]; } } int main() { hex(933); return 0; } - And recursively it is possible to write the same function? - Estet
- And why not, just what's the point? - Paul Shipilov
|
I would make it easier:
string hex(unsigned int n) { string res; while(n){ res = "0123456789abcdef"[n%16] + res; n /= 16; } return res; } int main() { cout << hex(933) << endl; cout << hex(15) << endl; cout << hex(84) << endl; } Here is a shorter version, with recursion:
void hex(unsigned int n) { if (n == 0) return; hex(n/16); cout << "0123456789abcdef"[n%16]; } int main() { hex(933); cout << endl; hex(15); cout << endl; hex(84); cout << endl; } And, of course, the simplest :)
int main() { cout << hex << 933 << endl; cout << hex << 15 << endl; cout << hex << 84 << endl; } |
std::cout << hex(933);write justhex(933);and you will be happy ... - Harrystd::cout << tempi.e. display the temp variable on the screen. If you want to output the result (or use it differently) after calling the function, then you need to collect the result in a line and then return this line - Mike