我是C新手,我一直在尋找一個定製函數在C中將字符串轉換爲整數,我碰到這個算法,除了一個部分是非常有意義的。 -'0'
究竟是做什麼的n = n * 10 + a[c] - '0';
?將字符串轉換爲數字時,爲什麼減去'0'?
int toString(char a[]) {
int c, sign, offset, n;
if (a[0] == '-') { // Handle negative integers
sign = -1;
}
if (sign == -1) { // Set starting position to convert
offset = 1;
}
else {
offset = 0;
}
n = 0;
for (c = offset; a[c] != '\0'; c++) {
n = n * 10 + a[c] - '0';
}
if (sign == -1) {
n = -n;
}
return n;
}
該算法沒有從我找到它的位置解釋,here。
見http://www.asciitable.com/ - 注意數字字符 – user2864740 2014-09-27 23:22:38
否,*字符*''0的關係(和值) ''的值是48,'\ 0''是0是NUL。 – user2864740 2014-09-27 23:28:48