You must initialise your result
. When you define
double result;
it is not guaranteed to be zero. It can have any value and will probably be garbage. Especially if every subsequent operation relies on result
having a valid value:
result = result * 10.0f + (str[n]-'0');
...
result = result/10.0f;
You should initialise your variable to
double result = 0.0;
A memory checker such as Valgrind can help you to find operations on uninitialised values.
There's also the issue Sourav Ghosh pointed out: sizeof
does not give you then length of a string. You should use strlen
from <string.h>
for that. But in your case, you don't really need it, because you already determine the length when you copy the string in loop
.
And, of, course, you should explicitly initialise pos
to zero as well. Otherwise, strings without a decimal point may not be parsed correctly.
(Finally, copying the string doesn't buy you anything, but introduces the danger of overwriting the temporary buffer of 30 chars.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…