atof使用atoi错误

时间:2015-01-18 21:11:32

标签: c while-loop atoi atof

这是一个atof函数,它将字符串转换为float,首先将字符串转换为整数,然后将整数除以10s,以便在保存deciaml点位置后得到实数

虽然条件为真,但程序没有输入负责省略小数点的第二个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;


}

1 个答案:

答案 0 :(得分:3)

您有一个额外的;,会将while语句置于无限循环中。

while(length>i);            //delete the decimal point to get integer number
               ^^ This is the problem.