我一直在看这段C代码,但不确定它到底在做什么。我不理解使用find语句的多个if语句。
int f(char *s) {
char *p = s;
int c = 1;
while (*p == ’ ’)
++p;
while (*p != ’\0’) {
if ( *p < ’0’ || *p > ’9’ ) {
printf("Error!\n"); return 0;
}
++p; }
for (--p; p >= s; --p) {
if (*p == ’ ’) *p = ’0’;
*p += c;
if (*p > ’9’) {
*p = ’0’; c = 1;
} else
c = 0;
if (c == 0) break;
}
if (c != 0) {
printf("Error!\n");
return 0;
}
return 1; }
答案 0 :(得分:1)
// return an integer given a character pointer, a string.
int f(char *s) {
// Set current position to start of string
char *p = s;
// Initialise carry flag to '1'.
int c = 1;
// Move position past leading spaces
while (*p == ’ ’)
++p;
// Check remaining characters are in the set {'0','1',..,'9'}
while (*p != ’\0’) {
// If they are not, return with an error
if ( *p < ’0’ || *p > ’9’ ) {
printf("Error!\n"); return 0;
}
++p; }
// Now counting back from the end of the string
for (--p; p >= s; --p) {
// Turn a space into a '0';
if (*p == ’ ’) *p = ’0’;
// Increment the digit by the value of the carry; one or zero
*p += c;
// This might cause a further carry, capture that
if (*p > ’9’) {
*p = ’0’; c = 1;
} else
c = 0;
// if no carry, break, else keep on with the carry
if (c == 0) break;
}
// If still carrying passed the end of the space, call an error.
if (c != 0) {
printf("Error!\n");
return 0;
}
return 1; }
本质上:如果输入是数字字符串,请加一个;否则,请加1。可能需要一个前导空格,并且如果输入全为9,则会使用它。