C语言实现atoi和atof函数


#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>

int ato_i(char *p) {
    assert(p);
    int k = 0;
    int sign = 1;
    while (*p) {
        if (isdigit(*p)) {
            k = k * 10 + *p - '0';
        } else if (k == 0) {
            if (*p == '-' && sign == 1) {
                sign = sign * (-1);
            }
            p++;
            continue;
        } else break;

        p++;
    }

    return k * sign;
}

double ato_f(char *p) {
    double val, power;
    int sign, i;
    for (;isspace(*p) && *p != '\0'; p++) ;
    sign = (*p == '-') ? -1 : 1;
    if (*p == '-' && *p == '+') p++;
    for (val = 0.0; isdigit(*p) && *p != '\0'; p++) {
        val = 10 * val + *p - '0';
    } 

    if (*p == '.') p++;

    for (power = 1.0; isdigit(*p) && *p != '\0'; p++) {
        val = 10 * val + *p - '0';
        power *= 10;
    }

    return sign * val / power;
}

double ato_fe(char *p) {
    double val, val2, power;
    int sign, sign2, i;
    for (;isspace(*p) && *p != '\0'; p++) ;
    sign = (*p == '-') ? -1 : 1;
    if (*p == '-' && *p == '+') p++;
    for (val = 0.0; isdigit(*p) && *p != '\0'; p++) {
        val = 10 * val + *p - '0';
    } 

    if (*p == '.') p++;

    for (power = 1.0; isdigit(*p) && *p != '\0'; p++) {
        val = 10 * val + *p - '0';
        power *= 10;
    }

    if (tolower(*p) == 'e') p++;
    sign2 = (*p++ == '-') ? -1 : 1;
    for (val2 = 0.0; isdigit(*p) && *p != '\0'; p++) {
        val2 = 10 * val2 + *p - '0';
    }

    if (sign2 == -1)
        return sign * val / power / pow(10, val2);
    else 
        return sign * val * pow(10, val2) / power;
}

long ato_l(char *p) {

}

int main(int argc, char **argv) {
    char *p = "123";
    char *p1 = "-123";
    char *p2 = "12a3";
    char *p3 = "  123";
    printf("p is %s, and ato_i(p) = %d \n", p, ato_i(p));
    printf("p1 is %s, and ato_i(p1) = %d \n", p1, ato_i(p1));
    printf("p2 is %s, and ato_i(p2) = %d \n", p1, ato_i(p2));
    printf("p3 is %s, and ato_i(p3) = %d \n", p1, ato_i(p3));

    char *s = "123.45";
    char *s2 = "123.45e-2";
    double d = ato_f(s);
    double d2 = ato_fe(s2);

    printf("ato_f = %f \n", ato_f(s));
    printf("ato_fe = %f \n", ato_fe(s2));
    return 0;
}


结果输出:

p is 123, and ato_i(p) = 123 
p1 is -123, and ato_i(p1) = -123 
p2 is -123, and ato_i(p2) = 12 
p3 is -123, and ato_i(p3) = 123 
ato_f = 123.450000 
ato_fe = 1.234500 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值