简单的C语音字符串和整数以及浮点数互转(递归实现)

代码如下:

  • int转字符串
void inttostr(int curnum,char** str )
{
    if (curnum!= 0)
    {
        inttostr(curnum / 10,str);
        **str = curnum % 10 + 48;
        (*str)++;
    }
}
  • double转字符串
void doutostr(double currnum,char* str)
{
    if (currnum == 0)
    {
        *str = '\0';
    }
    else if (currnum>0)
    {
        int currInt = 10 * currnum;
        *str = currInt + 48;
        doutostr(currnum * 10 - currInt, str + 1);
    }
}
  • 字符串转int
int strtoint(char* str,int currValue)
{
    if (str == NULL)
    {
        return 0;
    } 
    if (*str == '\0' || *str > '9' || *str < '0')
    {
        return currValue;
    }
    else
    {
        return strtoint(str + 1, currValue * 10 + (*str - 48));
    }
}
  • 字符串转double
double stringtodouble(char* numStr)
{
    if (numStr == NULL)
    {
        return 0;
    }

    double returnValue=0;
    char* start = numStr;
    char* point = numStr;
    bool isFushu = false;

    if (*point == '-')
    {
        isFushu = true;
        start++;
    }
    while (*point != '\0' && *point != '.')
    {
        point++;
    }
    if (*point == '.')
    {
        *point = '\0';
        returnValue = strtoint(start, 0) + strtodouble(point + 1);
    }
    else
    {
        returnValue = strtoint(start, 0);
    }
    if (isFushu)
    {
        returnValue = -returnValue;
    }
    return returnValue;
}

double strtodouble(char* str)
{
    if (str == NULL || *str > '9' || *str < '0')
    {
        return 0;
    }
    if (*str == '\0')
    {
        return 0;
    }
    else
    {
        return  0.1*( ( strtodouble(str+1) ) + (*str-48));
    }
}

猜你喜欢

转载自blog.csdn.net/zhanghedong526/article/details/46052407