I have this little code
void main()
{
int len,i;
int rta[64];
char numero[64];
scanf("%s",numero);
len = strlen(numero);
i=0;
for (i=0; i<len; i++){
rta[i]=(int)numero[i]*2;
}
printf(rta);
}
Whose input is 113
and result should be 226
, but instead it gives me the following resultb
The idea is to convert the numbers to int 's and then operate on them since I need it to read it as a string initially.
Any ideas?
Thank you!
You have some problems with the concept of character encoding .
To be brief: the double of a digit does not have to match the double of that encoded digit .
You enter
113
, but actually quite a different thing is stored in memory:Departure:
If we apply your algorithm by hand :
We get the following:
And why does only one 'b' appear?
This is more fun, and things like the endian of the machine come into play. To summarize, let's say that, in 32bits and little-endian , the number 49 is stored as
You try to read it as a character string , which is interpreted by 8 - bit packets ... and stops displaying when it reaches the first
0
.And we still have things to discuss, such as the influence of having declared
rta
as a formation ofint
... but we have already extended too much :-)Well, we're done now. Your corrected code, taking into account all the previous paragraph , would be:
As you can see, we carry out the operation in 3 steps:
Note that we do not take into account the possible overflow when multiplying a digit by 2... What happens if you enter
999
? :-)