[英]atoi function in C programming language K&R
I quite don't know what this loop does. 我完全不知道此循环的作用。
int atoi(char s[])
{
int i, n;
n = 0;
for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
n = 10 * n + (s[i] - '0');
return n;
}
This part I don't get: 这部分我不明白:
for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
n = 10 * n + (s[i] - '0');
I get the whole for loop inside parentheses, and what s[i] - '0' does. 我在括号内得到了整个for循环,以及s [i]-'0'的作用。 But I don't get what kind of operation is going on here --> n = 10 * n
. 但是我不知道这里要进行哪种操作-> n = 10 * n
。
I don't know what n is representing and why is multiplying 10. I know it's converting string of digits to numeric equivalent, but I just don't get the whole operation there. 我不知道n代表什么,为什么要乘10。我知道它会将数字字符串转换为等价的数字,但是我不了解整个操作。
But I don't get what kind of operation is going on here --> n = 10 * n 但是我不知道这里正在进行什么操作-> n = 10 * n
That's just how you build a number digit by digit. 这就是您逐步建立一个数字的方式。 It's basically the same as it would work if you were writing a calculator. 它基本上与您编写计算器时的工作原理相同。 If I wrote a simple calculator, here's how it would handle the input 5 4 7 : 如果我写了一个简单的计算器,这就是它处理输入5 4 7的方式 :
Basically, atoi
does, the exact same thing, but instead of reading each digit from button presses, it's reading them from a string. 基本上, atoi
确实做到了相同的事情,但是它不是从按键中读取每个数字,而是从字符串中读取它们。 Each time you read a new digit, you do n *= 10
to make room for that next digit, which just gets directly added on the end. 每次读取一个新数字时,您都将n *= 10
为下一个数字腾出空间,该数字将直接添加到末尾。
n
is the digits that has already been processed. n
是已经处理过的数字。 For instance, for the string "123"
, first, the program gets digit 1
, convert it to integer and store it in n
, and then get the next digit 2
, this is where n = 10 * n
is useful, the previous 1
is multiplied by 10
, and added to the next digit 2
, the result is 12
, and this is stored as the current n
. 例如,对于字符串"123"
,程序首先获取数字1
,将其转换为整数并将其存储在n
,然后获取下一个数字2
,这是n = 10 * n
有用的地方,前一个1
乘以10
,然后加到下一个数字2
,结果为12
,并将其存储为当前n
。
The same goes on, when processing 3
, the previous stored 12
is multiplied by 10
, results in 120
and added to 3
, ended as 123
as result. 同样地,当处理3
,先前存储的12
乘以10
,得到120
并加到3
,结果以123
结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.