これは、最初に文字列を整数に変換し、次に整数を 10 で割って、小数点位置を保存した後に実数を取得することにより、文字列を に変換するatof
関数です。float
条件は真ですが、プログラムは小数点の省略を担当する 2 番目の 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;
}