这个算法用Write great code Vol 1 book编写,用于将十进制数字串转换为整数值:
我不知道转换是如何发生的。请举例说明。
答案 0 :(得分:2)
/* warning: naive and unsafe implement. don't use it for important projects */
int strtod(const char *str)
{
int ret = 0;
while (*str)
ret = ret * 10 + *str++ - '0';
return ret;
}
答案 1 :(得分:1)
这是您的标准字符串到int转换算法:
char *s = "12345";
int res = 0; // 1. Initialize a variable with zero
while (*s) { // 2. If there are no more digits in the string...
int d = (*s++ - '0'); // 3. Fetch the next digit
res = 10*res + d; // 4. Multiply the variable by ten, and then...
} // 5. Go to step 2 and repeat.
答案 2 :(得分:1)
考虑字符串“1134”
String Variable
()1134 0
(1)134 0 * 10 + 1 = 1
1(1)34 1 * 10 + 1 = 11
11(3)4 11 * 10 + 3 = 113
113(4) 113 * 10 + 4 = 1134