尝试实现 atoi和atof函数

//
//  main.cpp
//  atoiAndatof
//
//  Created by CHEN on 15/9/6.
//  Copyright (c) 2015年 CHEN. All rights reserved.
//

#include <iostream>
#include <math.h>
#include <cstdio>

using namespace std;

int myatoi(char *pstr) {
    
    int intVal = 0; //最后返回的int值
    int sign = 1;   //1代表正数, -1代表负数
    
    //跳过字符串前面的空格
    while (*pstr == ' ')
        pstr++;
    
    //取得int值的符号
    if (*pstr == '-')
        sign = -1;
    if (*pstr == '-' || *pstr == '+')
        pstr++;
    
    while (*pstr >= '0' && *pstr <= '9') {
        //ASCII码中'0'的值是0x30
        intVal = intVal * 10 + ((int)*pstr - 0x30);
        pstr++;
    }
    
    return sign * intVal;
}

double myatof(char *pstr) {
    
    //firstVal 代表整数部分, secondVal 代表小数部分
    double firstVal = 0.0;
    double secondVal = 0.0;
    
    //secondLen 代表小数部分的位数
    double secondLen = 0.0;
    
    //+,- 符号
    double sign = 1.0;
    
    //跳过字符串前面的空格
    while (*pstr == ' ')
        pstr++;
    
    //取得int值的符号
    if (*pstr == '-')
        sign = -1;
    if (*pstr == '-' || *pstr == '+')
        pstr++;

    //取得整数部分
    while (*pstr <= '9' && *pstr >= '0') {
        //同myatoi中的步骤
        firstVal = firstVal * 10 + ((int)*pstr - 0x30);
        pstr++;
    }
    
    if (*pstr == '.') {
        pstr++;
    }
    
    while (*pstr <= '9' && *pstr >= '0') {
        secondLen ++;
        secondVal = secondVal * 10 + ((int)*pstr - 0x30);
        pstr++;
    }
    
    double temp = sign * (firstVal + secondVal / pow(10.0, secondLen));
    
    return temp;
}


int main(int argc, const char * argv[]) {
    // insert code here...
    char pint[100], pdouble[100];
    cin.getline(pint, 99);
    cin.getline(pdouble, 99);
    
    printf("%d\n", myatoi(pint));
    
    double temp = myatof(pdouble);
    printf("%.6f", temp);
    
    return 0;
}
 


用cout的时候对setpresicion函数不太明白,所以先用printf打印,函数功能是正确的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值