Old*_*ool -2 c++ string floating-point double
在这里,我试图将一串数字转换为相应的双数字.
double string_to_double ( const char* str)
{
int i = 0;
double* num = (double *)malloc(sizeof(double));
*num = 0;
int fract_fact = 10;
int size = strlen(str);
if ( str[0] != '.') // if its not starting with a point then take out the first decimal digit and place it in the number instead of 0.
*num = (str[i] - '0');
for ( i = 1; i < size; ++i){
if ( str[i] == '.'){
i++;
for (int j = i; j < size; ++j){ // after encountering point the rest of the part is fractional.
*num += (str[j] - '0') / fract_fact; // summing up the next fractional digit.
fract_fact *= 10; // increasing the farct_fact by a factor of 10 so that next fractional digit can be added rightly.
}
break;
}
*num = *num * 10 + ( str[i] - '0');
}
return *num;
}
Run Code Online (Sandbox Code Playgroud)
当我从main调用它时如下
cout << string_to_double("123.22");
Run Code Online (Sandbox Code Playgroud)
它的输出是
123
但为什么?我究竟做错了什么?
*num += (str[j] - '0') / fract_fact;
Run Code Online (Sandbox Code Playgroud)
应该
*num += (str[j] - '0') / (double)fract_fact;
Run Code Online (Sandbox Code Playgroud)
您的版本执行整数运算,总是计算为零.
不是你问的问题,但为什么要分配num?
double num;
num = ...
return num;
Run Code Online (Sandbox Code Playgroud)
更简单,它不会泄漏内存.