gpt4 book ai didi

将字符串转换为 C 中的 float (无 atof)

转载 作者:太空狗 更新时间:2023-10-29 16:52:24 24 4
gpt4 key购买 nike

我正在设计一个将字符串转换为 float 的函数。例如"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;
}

最佳答案

这是我的尝试:

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;
};

关于将字符串转换为 C 中的 float (无 atof),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4392665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com