要转换的字符串 [英] String to float conversion
问题描述
你好,
你能告诉我如何在不使用标准功能的情况下将字符串转换为浮点数,例如 atoi
, atof
, strtod
, sscanf
等
我的代码是:
Hello,
Could you please let me know how to convert string to float without using standard functions, like atoi
, atof
, strtod
, sscanf
etc.
My code is:
main()
{
char inputstr[]="123.45";
float result= 0.0F;
float temp;
int ndecimaldigit,i;
ndecimaldigit = 1;
for(i=0;i<=4;i++)
{
temp=inputstr[i] - '0';
ndecimaldigit *= 10;
temp /= ndecimaldigit;
result += temp;
}
printf("%f %f %d \n",result,temp,ndecimaldigit);
}
但我得到的输出为:0.122671 -0.000129 -31072
这是不正确。我需要输出为123.45
But i am getting output as: 0.122671 -0.000129 -31072
which is not correct. I need output as 123.45
推荐答案
尝试
Try
int main()
{
char inputstr[] = "123.45";
float result= 0.0f;
size_t len = sizeof(inputstr)-1;
size_t dotpos = 0;
for (size_t n = 0; n < len; n++)
{
if (inputstr[n] == '.')
{
dotpos = len - n - 1;
}
else
{
result = result * 10.0f + (inputstr[n]-'0');
}
}
while ( dotpos--)
{
result /= 10.0f;
}
printf("%f\n",result);
}
你也可以更改/添加下面的注释行,这样你也可以支持负值:
You may also change/add the commented lines below,so that you could support also negative values:
这个想法只是不触及CPallini为正值做的优秀短代码,只是将负值视为正值并乘以最后为-1使其为负。
The idea is simply by not touching the great short code CPallini made for positive values and just treat the negative value as positive and multiplying by -1 at the end to make it negative.
#include <stdio.h>
int main()
{
char inputstr[] = "-.45";
float result= 0.0f;
int len = sizeof(inputstr)-1;
int dotpos=0;
int n;
if (inputstr[0]=='-'||inputstr[0]=='+') //Added line to check sign.If the number is signed,
n=1; //set n to position 1.
else //(number is not signed)
n=0; //set n to position 0.
/*If the number was signed,then we set n to 1,so that we start with inputstr[1],and at the end if the number was negative we will multiply by -1.*/
for (; n < len; ++n) //n is already set to the position of the fisrt number.
if (inputstr[n] == '.')
dotpos = len - n - 1;
else
result = result * 10.0f + (inputstr[n]-'0');
while (dotpos--)
result /= 10.0f;
if (inputstr[0]=='-') //If inputstr[] is "negative",
result*=(-1); //multiply the number by -1,making it also negative.
printf("%f\n",result);
return 0;
}
我已将size_t更改为整数,因为我不知道如何使用它们。
I have changed size_t to integer,because I don't know how to use them.
这篇关于要转换的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!