在C中将字符串转换为float(不含atof)

smo*_*hie 9 c

我正在设计一个将字符串转换为浮点数的函数.例如"45.5"= 45.5

到目前为止我有这个.但它似乎没有用.请记住,我们不能使用任何C库函数,如atoi,atof甚至pow.

int str2float( char *s )
{
    int num = 0;
    int dec = 0;
    double i = 1.0;
    int ten = 1;
    /***** ADD YOUR CODE HERE *****/

    for(; *s != '\0'; s++)
    {
        if (*s == '.'){
            for(; *s != '\0'; s++){
                dec = (dec * CONT) + (*s - '0');
                i++;
            }
        }else{
            num = (num * CONT) + (*s - '0');
        }

    }
    for(;i!=0;i--){
        ten *= 10;
    }
    dec = dec / (ten);
    printf("%d", dec);
    num += dec;
    return num;  
}
Run Code Online (Sandbox Code Playgroud)

rus*_*lik 15

这是我的尝试:

float stof(const char* s){
  float rez = 0, fact = 1;
  if (*s == '-'){
    s++;
    fact = -1;
  };
  for (int point_seen = 0; *s; s++){
    if (*s == '.'){
      point_seen = 1; 
      continue;
    };
    int d = *s - '0';
    if (d >= 0 && d <= 9){
      if (point_seen) fact /= 10.0f;
      rez = rez * 10.0f + (float)d;
    };
  };
  return rez * fact;
};
Run Code Online (Sandbox Code Playgroud)