Hi.
I am trying to write a function that codes a number with arbitrary length. The number needs to be coded in a way such that every digit is increased by 1, and if the digit is 9, it should turn into a 0.
Here is my code:
int Code(int number, int length, int coded_number){
if (length == 0)
return coded_number;
int factor = pow(10, length-1); //avoiding recomputations
int digit = number / factor; //(int) pow(10, length-1);
int new_number = number - digit* factor; //(int)pow(10, length-1);
if (digit == 9)
digit = 0;
else
digit += 1;
coded_number += digit*factor; //(int)pow(10, length-1);
return Code(new_number, length-1, coded_number);
}
//Example calls
int a = Code(99999, 5, 0) // I get 111098 - I expect to get a 0 for this case
int b = Code(123456, 6, 0) // I get 234565
int c = Code(10524531, 8, 0) //I get 21635629
I really can't see what is wrong with my function, and why it doesn't code the whole number as it should.
Note:Inserting leading zeroes is not a part of the problem.
Any help would be appriciated.
Are you sure that you are calling the correct function pow?
If it is a C++ code then it shall not be compiled because the compiler does not know which of overloaded functions pow to call. You should write its call as
I don't see anything strange in pow...
I didn't change the code at all and when i tried it on the page you gave me it worked perfectly.
Later I did the change
pow(10.0, length - 1.0 );
but Dev-C++(on my PC) still displayed the same weird results.
I gues I'll have to test my code online from now on.
I compiled the code in C++ 4.7.2 (on the page). As for the output test, it was realy helpful, because now I know my compiler is "out of his mind" xD
I expected to get (and got this online):
factor for number 99999 is equal to 10000
factor for number 9999 is equal to 1000
factor for number 999 is equal to 100
factor for number 99 is equal to 10
factor for number 9 is equal to 1
From my compiler I get:
factor for number 99999 is equal to 9999
factor for number 9 is equal to 1000
factor for number 9 is equal to 99
factor for number 9 is equal to 10
factor for number 9 is equal to 1
Your code was compiled on-line because you are using unqualified name pow that is the name defined in the global namespace. However some compilers overloads these C names with C++ names. If you would use qualified name std::pow you could get an error.
In the end i figured that it would be easier to write my own pow function(with int arguments for my needs), which I did, and now everything works on my PC.
Thank you so much for all your help.