怎样将带小数点的字符型数据转换成浮点型数据?

# include 
# include 
# include 

int main(void){
    char str[10];
    printf("请输入一个带小数点的字符型数据: ");//类似于【0.98】等
    gets(str);
    double num = 0;
    int i = 0;
    double t = 10;
    while (str[i] != '\0')
    {
        if (str[i] >= '0' && str[i] <= '9')   
        {
            if (t == 10)
            {
                num = num * t + str[i] - 48;  //这里的str[i]表示ascii中所对应字符的十进制值减去48
            }
            else
            {
                num += (str[i] - 48) * t;
                t = t * 0.1;
            }
        }
        if (str[i] == '.')
        {
            t = 0.1;
        }
        i++;
    }
    if(str[i] == '-'){
        num = 0 - num;
    }
    printf("%f\n",num);
    system("pause");
    return 0;
}


你可能感兴趣的:(C语言)