I’m trying to write an octal to decimal conversion app.
The problem is the return value is 1 less than it should be, ex.:
INPUT: 2426 (OCT)
SHOULD RETURN: 1302 (DEC)
RETURNS: 1301 (DEC)
Any ideas what’s wrong? I’m using newest Code::Blocks if someone wants to know.
Here’s my code:
int oct2dec (int number) {
int system = 8;
int length = IntegerLength(number);
int power = length - 1;
int result = 0;
int partial = 0;
do {
partial = part_nr(number);
cout<<"czastka: "<<partial<<endl;
result = result + (partial * pow(system,power));
number = number - (partial * pow(10,power));
power--;
} while (number>0);
return result;
}
part_nr function:
int part_nr(int number) {
int multipler = 1;
int result = 0;
do {
int temp=number/multipler;
if(temp<10) result = temp;
multipler = multipler*10;
} while (result == 0);
return result;
}
IntegerLength function:
int IntegerLength(int value) {
int divisor = 10;
int length = 1;
while(value >= divisor)
{
value = (value - (value % divisor)) / divisor;
length ++;
}
return length;
}
(btw. I’ve translated variables from my native lang to english, so if you see any non-eng variable say so, i’ll correct it)
I have tested your code and it is outputting the value you claim to be expected. The only problem I encountered was with rounding. I changed the pow() function call to powf(), and then I cast the result of that function to integer.
This is the code I tested (VS2010 C++ Project):