尝试实现 atoi和atof函数
2015-09-06 19:49
507 查看
// // 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打印,函数功能是正确的。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua和C语言的交互详解
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- 关于C语言中参数的传值问题
- 简要对比C语言中三个用于退出进程的函数
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C语言中fchdir()函数和rewinddir()函数的使用详解
- C语言内存对齐实例详解
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题