//
// 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打印,函数功能是正确的。