#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
    Explain more clearly what you want to get, what does not work? ... - Harry
  • @Harry last balance with return temp re-displayed - Estet
  • Well, you deliberately withdraw it? Instead of std::cout << hex(933); write just hex(933); and you will be happy ... - Harry
  • @Harry, thanks! (I just learn a language recently, i.e. at return temp, does it not display the last remainder? or does it just temp all of the while-a just at the end through return temp displays?) - Estet
  • he returns nothing through return. you inside the function do std::cout << temp i.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

2 answers 2

 Как вариант: #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; }