Function Issue

I am not getting any syntax errors, however i have a logical error. My function singleNumConvert() does not seem to be working properly as it does not return the converted digit in binary. It should be passed a single integer than based on what the integer is, return the binary equivalent. It seems to just return a random integer. Not sure what I am missing, it has been a while since I have written in cpp.
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
#include <iostream>
#include <cstdlib>

void welcome (void);
int singleNumConvert(int digit);

using namespace std;

int main (){

int input = 12345;
int numberHolder[10] = {};
int singleNum = 0;
int arrayCounter = 0;

welcome();

while (input != 0){
singleNum = input % 10;
numberHolder[arrayCounter] = singleNumConvert(singleNum);
arrayCounter++;
input /= 10;
}

do{
cout<<numberHolder[arrayCounter];
arrayCounter--;
}
while(arrayCounter != 0);

exit(0);
}




void welcome (){

cout<<"This program convents integers from base 10 decimal to binaray.\n";
cout<<"Please enter a decimal number 10 digits long or less\n";

}



int singleNumConvert(int digit = 0){

if(digit == 0)
	digit = 0000;

else if(digit == 1)
	digit = 0001;

else if(digit == 2)
	digit = 0010;

else if(digit == 3)
	digit = 0011;

else if(digit == 4)
	digit = 0100;

else if(digit == 5)
	digit = 0101;

else if (digit == 6)
	digit = 0110;

else if (digit == 7)
	digit = 0111;

else if (digit == 8)
	digit = 1000;

else if (digit == 9)
	digit = 1001;

return digit;

}
Last edited on
An integer literal starting with 0 are interpreted in the octal numeral system (base 8) which is different from the decimal numeral system (base 10) that we are used to. This means that 0101 is not the same number as 101.

https://en.wikipedia.org/wiki/Octal
https://en.cppreference.com/w/cpp/language/integer_literal
The issue is the fuction should check the number and return the reassigned value however when ran it does not return the replaced value for digit.
Last edited on
The loop that prints the array elements is not correct. The first value it prints is always 0 (assuming it's within bounds) because it is the element after last value that you wrote in the previous loop. It also never prints the value of numberHolder[0].

If you pass the value 5 to singleNumConvert you want it to return the value 101 (one hundred and one)? At the moment it returns the value 65 because 101 in the octal numeral system is the same as the value 65 in the decimal numeral system. If you want to return 101 you need to write it without 0 in front because otherwise it will be interpreted as an octal number.
Last edited on
Topic archived. No new replies allowed.