今天整nodejs实在不行,npm和nodejs在源上版本不兼容,install一直出问题。于是不想整了。 写了下很久没有写的c代码,好吧。。无聊!在标准库stdlib中以下函数均已实现
int atoi(const char *nptr); long atol(const char *nptr); long long atoll(const char *nptr); long long atoq(const char *nptr); double atof(const char *nptr); double strtod(const char *nptr, char **endptr); float strtof(const char *nptr, char **endptr); long double strtold(const char *nptr, char **endptr);
今天无聊,自己写了几个实现下:
#include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #define MAX_LENGTH 15 void swap(char *a, char *b) { char t = *a; *a = *b; *b = t; return; } int atoi(const char *s) { int len = strlen(s); int res = 0; int i = 0; int sign = 0; if(s[0] == '-') sign = i = 1; for (; i < len; ++i) { if (!isdigit(s[i])) { fprintf(stderr, "%s is not a Integer!\n", s); exit(1); } res *= 10; res += (s[i] - '0'); } return sign == 1 ? -res : res; } char *itoa(const int n, char *dest) { int m = n; int i, j; int cur = 0; int sign = 0; memset(dest, 0, sizeof(char) * MAX_LENGTH); if (m < 0) { dest[cur++] = '-'; m *= -1; sign = 1; } while (m) { i = m % 10; dest[cur++] = '0' + i; m /= 10; } dest[cur] = 0; j = strlen(dest) - 1; i = sign ? 1 : 0; for(; i != j; i++, j--) swap(&dest[i], &dest[j]); return dest; } double atof(const char *s) { int len = strlen(s); int i = 0; int sign = 0; /* 符号位, 负数1,正数0 */ int int_part = 0; /* 整数部分 */ double point_part = 0; /* 小数部分 */ double res; /* 最后结果数值部分,不包括符号位 */ if (s[0] == '-') sign = i = 1; for (; i < len && s[i] != '.'; ++i) { if (!isdigit(s[i])) { fprintf(stderr, "%s is not a number!\n", s); exit(1); } int_part *= 10; int_part += (s[i] - '0'); } double base = 0.1; /* 当前小数位 */ for (++i; i < len; i++) { if (!isdigit(s[i])) { fprintf(stderr, "%s is not a number!\n", s); exit(1); } point_part += ((s[i] - '0') * base); base *= 0.1; } res = int_part + point_part; return sign ? -res : res; }