0
I am doing a function in C, which given a fractional part "frac" of a number in base 10, and another numerical base, returns the same fractional part in the desired base.
To do this, I allocate a char vector "Ret", which will shape the entire portion of the multiplication between the fractional part and the desired base of the conversion. I repeat this process until the variable "frac" is zeroed, that is, until there are only zeros after the comma.
The function works with some fractional numbers like the ,00244140625 to the base 16, for example. But when testing with the number ,076444444 (periodic decimation) and base 12, it returns the correct number followed by a directory of my computer.
char* dezParaOutraParteFracionaria(double frac, int base)
{
char *ret = (char*)malloc(MAX*sizeof(char));
int tamanhoDoNumero = 0;
while(frac != 0)
{
frac = frac * base;
int parteInteira = (int) frac;
frac = frac - parteInteira;
ret[tamanhoDoNumero++] = transformarCharDaBase10(parteInteira);
printf("%s\n", ret);
}
return ret;
}
By checking the prints made, you have:
0¶ã
0Bã
0B0
0B01
0B011
0B0119
0B0119A
0B0119A7P☺ã
0B0119A7A☺ã
0B0119A7A5ã
0B0119A7A56
0B0119A7A569
0B0119A7A5695
0B0119A7A56953
0B0119A7A569538
0B0119A7A5695385eDrive=C:\Users\user\Onej.ÐÞ;¾
0B0119A7A56953858Drive=C:\Users\user\Onej.ÐÞ;¾
0B0119A7A569538588rive=C:\Users\user\Onej.ÐÞ;¾
0B0119A7A5695385884ive=C:\Users\user\Onej.ÐÞ;¾
0B0119A7A56953858841ve=C:\Users\user\Onej.ÐÞ;¾
0B0119A7A569538588416e=C:\Users\user\Onej.ÐÞ;¾
0B0119A7A569538588416e=C:\Users\user\Onej.ÐÞ;¾
It should be noted that 0B0119A7A569538588416 is properly converted to base 12, but the e=C: Users user Onej.ːÞ;¾ has no known origin.
What could be going wrong?
You forgot to add the ending character ' 0' to the end of the string. , hence picking up memory junk. Put:
ret[tamanhoDoNumero] = '\0'
before thereturn
.– anonimo
For your test put
ret[tamanhoDoNumero] = '\0';
beforeprintf("%s\n", ret);
. When you close tests you can put it just before Return.– anonimo