Advertisement
JosepRivaille

P56549: Canvis de Base

Apr 4th, 2015
2,529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.74 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5. void canvi_base_2(int n) {
  6.     int q;
  7.     q = n/2;
  8.     if (q != 0) canvi_base_2(q);
  9.     cout << n - 2 * q;
  10. }
  11.  
  12. void canvi_base_8(int n) {
  13.     int q;
  14.     q = n/8;
  15.     if (q != 0) canvi_base_8(q);
  16.     cout << n - 8 *q;
  17. }
  18.  
  19. void canvi_base_16(int n) {
  20.     int q;
  21.     char k;
  22.     q = n/16;
  23.     if (q != 0) canvi_base_16(q);
  24.     if ((n - 16 * q) >= 10) { //Si està entre 10 o 16 s'expressa entre A i F
  25.         k = 'A' + (n%16) - 10;
  26.         cout << k;
  27.     }
  28.     else cout << n - 16  * q;
  29. }
  30.  
  31. //Pre: Llegeix un enter
  32. //Post: L'escriu en binari, octal i hexadecimal
  33. int main() {
  34.     int n;
  35.     while (cin >> n) {
  36.         cout << n << " = ";
  37.         canvi_base_2(n);
  38.         cout << ", ";
  39.         canvi_base_8(n);
  40.         cout << ", ";
  41.         canvi_base_16(n);
  42.         cout << endl;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement