这是一个将字符串转换为的atof
函数,float
首先将字符串转换为整数,然后将整数除以 10 以在保存小数点位置后得到实数
尽管条件为真,但程序并没有进入第二个负责省略小数点的 while 循环
我在 ubuntu14.04 上使用 Geany 1.23.1
#include <stdio.h>
#include <math.h>
#include <string.h>
double atof1(char num[]); //converts from character to float
// by converting string to integer first then divide by
//10 to the power of the count of fraction part
int main()
{
char test[]="123.456";
printf("%f\n",atof1(test));
return 0;
}
double atof1(char num[])
{
int dp=0; //decimal point position
int length=strlen(num);
int i=0;
while(dp==0) //increment till you find decimal point
{
if(num[i]=='.')
{
dp=i; //decimal point found
break;
}
else i++;
}
printf("%d %d\n",i,length);
while(length>i); //delete the decimal point to get integer number
{
num[i]=num[i+1]; //deletes deicmal point
i++;
printf("%d",i);
}
int integer_number=atoi(num); //integer number of the string
double final =integer_number/(pow(10,(length-dp-1)));//divide by 10s to get the float according to position of the '.'
return final;
}