A. atoi,字符串转整数
使用assert强制规定字符串一定是合法的,剩下的就是正负号了。
#include <stdio.h>
#include <assert.h>
int atoi(const char* str) {
if (str == NULL)
return 0;
int num = 0, i = 0;
bool neg = false;
if (str[0] == '-') {
neg = true;
++i;
}
while (str[i] != '\0') {
assert (str[i] >= '0' && str[i] <= '9');
num *= 10;
num += int(str[i]-'0');
++i;
}
if (neg)
return -num;
return num;
}
int main() {
printf("%d\n", atoi("233"));
printf("%d\n", atoi("980"));
printf("%d\n", atoi("066"));
printf("%d\n", atoi("-123"));
return 0;
}
B. stof,字符串转float
这里只实现了简单的浮点数形式,没有实现像1e-10这样子的转化。
一开始输出的时候,以为是精度的问题,然后发现,转化的精度方面不会差太多,主要是float表示不了那么精确的浮点数,所以导致结果输出与原始数字有点不同:
233.0000000000, real=233.0000000000
3.1415927410, real=3.1415927410
123.4567871094, real=123.4567871094
-123.4567871094, real=-123.4567871094
#include <stdio.h>
#include <assert.h>
/*
// version 1
float stof(const char* str) {
float num = 0;
int i = 0;
for (i = 0; str[i] != '\0' && str[i] != '.'; ++i) {
assert(str[i] >= '0' && str[i] <= '9');
num *= 10;
num += int(str[i] - '0');
}
if (str[i] == '\0')
return num;
float digit = 0.0, div = 1.0;
for (++i; str[i] != '\0' && str[i] != '.'; ++i) {
digit *= 10.0f;
digit += int(str[i] - '0');
div *= 10.0f;
}
return digit/div + num;
}*/
// version 2: maybe more precise
float stof(const char* str) {
if (str == NULL)
return 0.0f;
float num = 0;
int i = 0;
bool neg = false;
if (str[0] == '-') {
neg = true;
++i;
}
while(str[i] != '\0' && str[i] != '.') {
assert(str[i] >= '0' && str[i] <= '9');
num *= 10;
num += int(str[i] - '0');
++i;
}
if (str[i] == '\0')
return (neg) ? -num : num;
int start = i + 1, end = start;
while (str[end] != '\0' && str[end] != '.')
++end;
float digit = 0.0f;
for (int j = end-1; j >= start; --j) {
assert(str[j] >= '0' && str[j] <= '9');
digit += int(str[j] - '0');
digit *= 0.1f;
}
return (neg) ? -(digit + num) : (digit + num);
}
int main() {
float a = 233.0f, b = 3.1415928f, c = 123.456789f;
printf("%.10f,\t real=%.10f\n\n", stof("233"), a);
printf("%.10f,\t real=%.10f\n\n", stof("3.1415928"), b);
printf("%.10f,\t real=%.10f\n\n", stof("123.456789"), c);
printf("%.10f,\t real=%.10f\n\n", stof("-123.456789"), -c);
return 0;
}