atoi的递归实现

时间:2017-06-28 21:15:59

标签: c atoi

我正在尝试在C中实现atoi函数。但是,每当我使用测试字符串“856”时,结果int将是855.我尝试了很多测试用例但结果将是相同的(例如“4756” - > 4755)。下面的代码是我错误的解决方案。

#include <math.h>
#include <stdio.h>
int count = 0;
void atoi(char * str){
    static int power = 0;
    char * next = str;
    next++;
    if(*next != '\0' && next != NULL){
        atoi(next);
        power++;
        //printf("%f\n",((*str) - '0') * pow(10, power)); 
        count += ((*str) - '0') * pow(10, power);
    }
    else{
        //printf("%f\n",((*str) - '0') * pow(10, power));
        count += ((*str) - '0') * pow(10, power);
    }
}
int main(){
    char * string = (char *)malloc(sizeof(char)*3);
    string = "457";
    atoi(string);
    printf("%d",count);
}

请您检查一下为什么会这样?

0 个答案:

没有答案