Help with code

I have this code and it works perfectly except Hex=0 doesn't work, i tried to add IF statement but it added 0 to all the 255 the outputs of Hex, can someone tell me what to do please. thanks


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
  #include<iostream>
using namespace std;




// Decimal TO Binary 
////////////////////

void binary(int number) {
	int remain;

	if (number <= 1) {
		cout << number;
		return;
	}

	remain = number % 2;
	binary(number >> 1);
	cout << remain;
}



// Decimal TO HEX
//////////////////

void Hex(int number, int base)
{
	
	if (number > 0)
	{
		Hex(number / base, base);
		switch (number%base)
		{
		case 0:
			cout << "0";
			break;
		case 10:
			cout << "A";
			break;
		case 11:
			cout << "B";
			break;
		case 12:
			cout << "C";
			break;
		case 13:
			cout << "D";
			break;
		case 14:
			cout << "E";
			break;
		case 15:
			cout << "F";
			break;
		default:
			cout << number%base;
			break;
		}
	}

}




int main()
{
	int decimalNumber = 0;

	for (int i = 0; decimalNumber < 255; i++)
	{
		decimalNumber = i;
		cout << "Decimal " << decimalNumber << "       " << "Binary= "; binary(decimalNumber);
		cout << "       " << "Hex= "; Hex(decimalNumber, 16);
		cout << endl;
	}

	system("Pause");
	return 0;
}






closed account (48T7M4Gy)
1
2
3
4
5
6
7
default:
      cout << number%base;
      break;
     }
  }
   else // <---
      cout << "0";// <--- 
Last edited on
I still get 0 behind every hex number,
Like
01
02
03
.
.
.
0 FF

i dont want that zero :(
closed account (48T7M4Gy)
Bummer. I see what you mean.

One problem that stood out even on looking at it at the first time is the switch has case 0 and yet the if statement makes that impossible.

I think you need to revisit your recursion and integrate a while statement instead of if to end the recursion. I suspect you need to incorporate both number/base as well as number%base.
Topic archived. No new replies allowed.